diff --git a/.gitmodules b/.gitmodules index e8a18a3d6af94236f5d743c23428196e6a020423..199c875fc6d8c07ddf1a1a019b90cabf5f9562b0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,45 +1,45 @@ -[submodule "ttcn/LibCommon"] - path = ttcn/LibCommon - url = https://forge.etsi.org/rep/LIBS/LibCommon.git -[submodule "ttcn/LibIts"] - path = ttcn/LibIts - url = https://forge.etsi.org/rep/LIBS/LibIts.git - branch = devel -[submodule "ttcn/AtsCAM"] - path = ttcn/AtsCAM - url = https://forge.etsi.org/rep/ITS/ttcn/ats_cam_ts102868-3.git - branch = devel -[submodule "ttcn/AtsDENM"] - path = ttcn/AtsDENM - url = https://forge.etsi.org/rep/ITS/ttcn/ats_denm_ts102869-3.git - branch = devel -[submodule "ttcn/AtsGeoNetworking"] - path = ttcn/AtsGeoNetworking - url = https://forge.etsi.org/rep/ITS/ttcn/ats_gn_ts102871-3.git - branch = devel -[submodule "ttcn/AtsBTP"] - path = ttcn/AtsBTP - url = https://forge.etsi.org/rep/ITS/ttcn/ats_btp_ts102870-3.git - branch = devel -[submodule "ttcn/AtsIPv6OverGeoNetworking"] - path = ttcn/AtsIPv6OverGeoNetworking - url = https://forge.etsi.org/rep/ITS/ttcn/ats_gnipv6_ts102859-3.git - branch = devel -[submodule "ttcn/AtsPki"] - path = ttcn/AtsPki - url = https://forge.etsi.org/rep/ITS/ttcn/ats_pki_ts103525-3.git - branch = devel -[submodule "ttcn/AtsIS"] - path = ttcn/AtsIS - url = https://forge.etsi.org/rep/ITS/ttcn/ats_ts103191-3.git - branch = devel -[submodule "ttcn/AtsSecurity"] - path = ttcn/AtsSecurity - url = https://forge.etsi.org/rep/ITS/ttcn/ats_sec_ts103096-3.git - branch = devel -[submodule "ttcn/modules/titan.TestPorts.HTTPmsg/module"] - path = ttcn/modules/titan.TestPorts.HTTPmsg/module - url = https://github.com/eclipse/titan.TestPorts.HTTPmsg.git -[submodule "ttcn/modules/titan.TestPorts.Common_Components.Abstract_Socket/module"] - path = ttcn/modules/titan.TestPorts.Common_Components.Abstract_Socket/module - url = https://github.com/eclipse/titan.TestPorts.Common_Components.Abstract_Socket.git +[submodule "ttcn/LibCommon"] + path = ttcn/LibCommon + url = https://forge.etsi.org/rep/LIBS/LibCommon.git +[submodule "ttcn/LibIts"] + path = ttcn/LibIts + url = https://forge.etsi.org/rep/LIBS/LibIts.git + branch = devel +[submodule "ttcn/AtsCAM"] + path = ttcn/AtsCAM + url = https://forge.etsi.org/rep/ITS/ttcn/ats_cam_ts102868-3.git + branch = devel +[submodule "ttcn/AtsDENM"] + path = ttcn/AtsDENM + url = https://forge.etsi.org/rep/ITS/ttcn/ats_denm_ts102869-3.git + branch = devel +[submodule "ttcn/AtsGeoNetworking"] + path = ttcn/AtsGeoNetworking + url = https://forge.etsi.org/rep/ITS/ttcn/ats_gn_ts102871-3.git + branch = devel +[submodule "ttcn/AtsBTP"] + path = ttcn/AtsBTP + url = https://forge.etsi.org/rep/ITS/ttcn/ats_btp_ts102870-3.git + branch = devel +[submodule "ttcn/AtsIPv6OverGeoNetworking"] + path = ttcn/AtsIPv6OverGeoNetworking + url = https://forge.etsi.org/rep/ITS/ttcn/ats_gnipv6_ts102859-3.git + branch = devel +[submodule "ttcn/AtsPki"] + path = ttcn/AtsPki + url = https://forge.etsi.org/rep/ITS/ttcn/ats_pki_ts103525-3.git + branch = devel +[submodule "ttcn/AtsIS"] + path = ttcn/AtsIS + url = https://forge.etsi.org/rep/ITS/ttcn/ats_ts103191-3.git + branch = devel +[submodule "ttcn/AtsSecurity"] + path = ttcn/AtsSecurity + url = https://forge.etsi.org/rep/ITS/ttcn/ats_sec_ts103096-3.git + branch = devel +[submodule "ttcn/modules/titan.TestPorts.HTTPmsg/module"] + path = ttcn/modules/titan.TestPorts.HTTPmsg/module + url = https://github.com/eclipse/titan.TestPorts.HTTPmsg.git +[submodule "ttcn/modules/titan.TestPorts.Common_Components.Abstract_Socket/module"] + path = ttcn/modules/titan.TestPorts.Common_Components.Abstract_Socket/module + url = https://github.com/eclipse/titan.TestPorts.Common_Components.Abstract_Socket.git diff --git a/Makefile b/Makefile index 97cfa1118df543922a24882841db224e75678545..a771918ca973fcac2531b7e1440b845fe16fb951 100644 --- a/Makefile +++ b/Makefile @@ -1,150 +1,150 @@ --include config.mk - -ifeq (,$(ATS)) - $(error ATS shall be defined) -endif - -ifeq (,$(TOPDIR)) - TOPDIR := . -endif - -ifeq (,$(TTCN3_DIR)) - $(error TTCN3_DIR shall be defined in config.mk) -endif - -export ASN1C_PATH - -first: all - -define IncludeModule -undefine sources -undefine modules -undefine includes -include $(1)/module.mk -$$(foreach S, $$(sources), $$(eval all_sources += $$(if $$(filter /%, $$(S)), $$(TOPDIR)/$$(S), $(1)/$$(S)))) -$$(foreach I, $$(includes), $$(eval all_includes += $$(if $$(filter /%, $$(I)), $$(TOPDIR)/$$(I), $(1)/$$(I)))) -$$(foreach M, $$(modules), $$(eval $$(call IncludeModule, $$(if $$(filter /%, $$(M)), $$(TOPDIR)/$$(M), $(1)/$$(M))))) -endef - -all_includes := $(TTCN3_DIR)/include $(TTCN3_DIR)/src $(TOPDIR)/ccsrc/Framework /usr/include/jsoncpp -defines += TITAN_RUNTIME_2 _NO_SOFTLINKS_ $(ATS) -libs += $(TTCN3_DIR)/lib/libttcn3-rt2-parallel.a -lstdc++fs - -ifeq (Windows_NT,$(OS)) -# Silence linker warnings. -LDFLAGS += -Wl,--enable-auto-import,--enable-runtime-pseudo-reloc -defines += WIN32 -libs += $(patsubst %, -L%/lib, $(OPENSSL_DIR)) -all_includes += $(addsuffix /include, $(OPENSSL_DIR)) -libs += $(WPCAP_DLL_PATH) -else -defines += LINUX -libs += -lpcap -lrt -lpthread -endif - -libs += -lssl -lcrypto -lxml2 -ljsoncpp - -$(eval $(call IncludeModule, $(TOPDIR)/ttcn/$(ATS))) - -outdir := $(TOPDIR)/build/$(ATS) -bindir := $(TOPDIR)/bin - -sources := $(sort $(all_sources)) -includes := $(outdir) $(outdir)/.. $(outdir)/../asn1 $(all_includes) $(NPCAP_INCLUDE) - -ifeq (Windows_NT,$(OS)) - EXE=.exe -endif - -ttcn_sources := $(filter %.ttcn , $(sources)) -ttcn3_sources := $(filter %.ttcn3, $(sources)) -asn_sources := $(filter %.asn, $(sources)) -asn1_sources := $(filter %.asn1, $(sources)) - -tt_sources := $(ttcn_sources) $(ttcn3_sources) $(asn_sources) $(asn1_sources) -cc_sources := $(filter %.cc, $(sources)) - -gen_ttcn_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn, %.cc, $(ttcn_sources)))) -gen_ttcn_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn, %.hh, $(ttcn_sources)))) -gen_ttcn3_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn3, %.cc, $(ttcn3_sources)))) -gen_ttcn3_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn3, %.hh, $(ttcn3_sources)))) -gen_asn_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn, %.cc, $(asn_sources)))) -gen_asn_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn, %.hh, $(asn_sources)))) -gen_asn1_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn1, %.cc, $(asn1_sources)))) -gen_asn1_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn1, %.hh, $(asn1_sources)))) - -gen_sources := $(gen_ttcn_sources) $(gen_ttcn3_sources) $(gen_asn_sources) $(gen_asn1_sources) -gen_headers := $(gen_ttcn_headers) $(gen_ttcn3_headers) $(gen_asn_headers) $(gen_asn1_headers) - -gen_objects := $(patsubst %.cc, %.o, $(gen_sources)) -cc_objects := $(patsubst %.cc, $(outdir)/%.o, $(cc_sources)) - -.PHONY: all FORCE echo - -all: $(bindir) $(outdir) $(bindir)/$(ATS)$(EXE) - -echo_sources: - @echo -e "$(addsuffix \n,$(all_sources))" - -echo: echo_sources - @echo -e "sources:\n $(addsuffix \n, $(sources))" - @echo -e "gen_sources:\n $(addsuffix \n, $(gen_sources))" - @echo -e "gen_objects:\n $(addsuffix \n, $(gen_objects))" - @echo -e "cc_objects:\n $(addsuffix \n, $(cc_objects))" - @echo -e "includes:\n $(addsuffix \n, $(includes))" - @echo -e "defines: $(addsuffix \n, $(defines))" - -clean: - rm -f $(outdir)/$(ATS)$(EXE) $(gen_objects) $(gen_sources) $(gen_headers) $(cc_objects) $(outdir)/.generate $(outdir)/../libItsAsn.so -# rm -f $(outdir)/asn1/*.so $(outdir)/asn1/*.o $(outdir)/asn1/*.c $(outdir)/asn1/*.h $(outdir)/asn1/Makefile.am.libasncodec - -regen: force_regen $(outdir)/.generate -force_regen: - rm -f $(outdir)/.generate - -t3q: all - @echo -e "Code checking in progress..." - @java -Xmx3g -Xss512m -jar $(T3Q_PATH)/t3q.jar --config $(T3Q_PATH)/$(T3Q_CONFIG) $(tt_sources) > $(outdir)/t3q.out 2>&1 ; cd - - @echo -e "Code checking in done..." - @echo -e "Output file is located here: $(outdir)/t3q.out" - -t3d: all - @echo -e "TTCN-3 doc generation in progress..." - @java -Xmx3g -Xss512m -jar $(T3D_PATH)/t3d.jar --config $(T3D_PATH)/$(T3D_CONFIG) $(tt_sources) > $(outdir)/t3d.out 2>&1 ; cd - - @echo -e "TTCN-3 doc generation done..." - @echo -e "Output file is located here: $(outdir)/t3d.out" - -$(outdir) $(bindir): - mkdir -p $@ - -$(bindir)/$(ATS)$(EXE): $(outdir)/../asn1/libItsAsn.a $(gen_objects) $(cc_objects) - g++ -g -O0 -o $@ $(LDFLAGS) $(gen_objects) $(cc_objects) $(outdir)/../asn1/libItsAsn.a $(libs) - -$(gen_objects) :%.o :%.cc - g++ -g -O0 -c $(addprefix -D, $(defines)) $(addprefix -I, $(includes)) -o $@ $< - -$(cc_objects) : $(outdir)/%.o : %.cc - mkdir -p $(dir $@) - g++ -g -O0 -c $(addprefix -D, $(defines)) $(addprefix -I, $(includes)) -o $@ $< - -#$(gen_sources): -# $(TTCN3_DIR)/bin/compiler -n -e -L -R -U none -o $(outdir) $(tt_sources) - -$(gen_sources): $(outdir)/.generate - -$(outdir)/.generate: Makefile $(tt_sources) - $(TTCN3_DIR)/bin/compiler -w -d -e -f -g -l -L -R -U none -x -X -o $(outdir) $(tt_sources) - touch $@ - -$(bindir)/libItsAsn.so: $(outdir)/asn1/libItsAsn.so - cp -f $< $@ - -$(outdir)/../asn1/libItsAsn.a: FORCE - mkdir -p $(outdir)/../asn1 - $(MAKE) -C $(outdir)/../asn1 -f ../../asn1/Makefile - -$(foreach S, $(ttcn_sources), $(eval $(outdir)/$(notdir $(patsubst %.ttcn, %.cc, $(S))): $(S))) -$(foreach S, $(ttcn3_sources), $(eval $(outdir)/$(notdir $(patsubst %.ttcn3, %.cc, $(S))): $(S))) -$(foreach S, $(asn_sources), $(eval $(outdir)/$(notdir $(patsubst %.asn, %.cc, $(S))): $(S))) -$(foreach S, $(asn1_sources), $(eval $(outdir)/$(notdir $(patsubst %.asn1, %.cc, $(S))): $(S))) - +-include config.mk + +ifeq (,$(ATS)) + $(error ATS shall be defined) +endif + +ifeq (,$(TOPDIR)) + TOPDIR := . +endif + +ifeq (,$(TTCN3_DIR)) + $(error TTCN3_DIR shall be defined in config.mk) +endif + +export ASN1C_PATH + +first: all + +define IncludeModule +undefine sources +undefine modules +undefine includes +include $(1)/module.mk +$$(foreach S, $$(sources), $$(eval all_sources += $$(if $$(filter /%, $$(S)), $$(TOPDIR)/$$(S), $(1)/$$(S)))) +$$(foreach I, $$(includes), $$(eval all_includes += $$(if $$(filter /%, $$(I)), $$(TOPDIR)/$$(I), $(1)/$$(I)))) +$$(foreach M, $$(modules), $$(eval $$(call IncludeModule, $$(if $$(filter /%, $$(M)), $$(TOPDIR)/$$(M), $(1)/$$(M))))) +endef + +all_includes := $(TTCN3_DIR)/include $(TTCN3_DIR)/src $(TOPDIR)/ccsrc/Framework /usr/include/jsoncpp +defines += TITAN_RUNTIME_2 _NO_SOFTLINKS_ $(ATS) +libs += $(TTCN3_DIR)/lib/libttcn3-rt2-parallel.a -lstdc++fs + +ifeq (Windows_NT,$(OS)) +# Silence linker warnings. +LDFLAGS += -Wl,--enable-auto-import,--enable-runtime-pseudo-reloc +defines += WIN32 +libs += $(patsubst %, -L%/lib, $(OPENSSL_DIR)) +all_includes += $(addsuffix /include, $(OPENSSL_DIR)) +libs += $(WPCAP_DLL_PATH) +else +defines += LINUX +libs += -lpcap -lrt -lpthread +endif + +libs += -lssl -lcrypto -lxml2 -ljsoncpp + +$(eval $(call IncludeModule, $(TOPDIR)/ttcn/$(ATS))) + +outdir := $(TOPDIR)/build/$(ATS) +bindir := $(TOPDIR)/bin + +sources := $(sort $(all_sources)) +includes := $(outdir) $(outdir)/.. $(outdir)/../asn1 $(all_includes) $(NPCAP_INCLUDE) + +ifeq (Windows_NT,$(OS)) + EXE=.exe +endif + +ttcn_sources := $(filter %.ttcn , $(sources)) +ttcn3_sources := $(filter %.ttcn3, $(sources)) +asn_sources := $(filter %.asn, $(sources)) +asn1_sources := $(filter %.asn1, $(sources)) + +tt_sources := $(ttcn_sources) $(ttcn3_sources) $(asn_sources) $(asn1_sources) +cc_sources := $(filter %.cc, $(sources)) + +gen_ttcn_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn, %.cc, $(ttcn_sources)))) +gen_ttcn_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn, %.hh, $(ttcn_sources)))) +gen_ttcn3_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn3, %.cc, $(ttcn3_sources)))) +gen_ttcn3_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.ttcn3, %.hh, $(ttcn3_sources)))) +gen_asn_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn, %.cc, $(asn_sources)))) +gen_asn_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn, %.hh, $(asn_sources)))) +gen_asn1_sources := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn1, %.cc, $(asn1_sources)))) +gen_asn1_headers := $(addprefix $(outdir)/, $(notdir $(patsubst %.asn1, %.hh, $(asn1_sources)))) + +gen_sources := $(gen_ttcn_sources) $(gen_ttcn3_sources) $(gen_asn_sources) $(gen_asn1_sources) +gen_headers := $(gen_ttcn_headers) $(gen_ttcn3_headers) $(gen_asn_headers) $(gen_asn1_headers) + +gen_objects := $(patsubst %.cc, %.o, $(gen_sources)) +cc_objects := $(patsubst %.cc, $(outdir)/%.o, $(cc_sources)) + +.PHONY: all FORCE echo + +all: $(bindir) $(outdir) $(bindir)/$(ATS)$(EXE) + +echo_sources: + @echo -e "$(addsuffix \n,$(all_sources))" + +echo: echo_sources + @echo -e "sources:\n $(addsuffix \n, $(sources))" + @echo -e "gen_sources:\n $(addsuffix \n, $(gen_sources))" + @echo -e "gen_objects:\n $(addsuffix \n, $(gen_objects))" + @echo -e "cc_objects:\n $(addsuffix \n, $(cc_objects))" + @echo -e "includes:\n $(addsuffix \n, $(includes))" + @echo -e "defines: $(addsuffix \n, $(defines))" + +clean: + rm -f $(outdir)/$(ATS)$(EXE) $(gen_objects) $(gen_sources) $(gen_headers) $(cc_objects) $(outdir)/.generate $(outdir)/../libItsAsn.so +# rm -f $(outdir)/asn1/*.so $(outdir)/asn1/*.o $(outdir)/asn1/*.c $(outdir)/asn1/*.h $(outdir)/asn1/Makefile.am.libasncodec + +regen: force_regen $(outdir)/.generate +force_regen: + rm -f $(outdir)/.generate + +t3q: all + @echo -e "Code checking in progress..." + @java -Xmx3g -Xss512m -jar $(T3Q_PATH)/t3q.jar --config $(T3Q_PATH)/$(T3Q_CONFIG) $(tt_sources) > $(outdir)/t3q.out 2>&1 ; cd - + @echo -e "Code checking in done..." + @echo -e "Output file is located here: $(outdir)/t3q.out" + +t3d: all + @echo -e "TTCN-3 doc generation in progress..." + @java -Xmx3g -Xss512m -jar $(T3D_PATH)/t3d.jar --config $(T3D_PATH)/$(T3D_CONFIG) $(tt_sources) > $(outdir)/t3d.out 2>&1 ; cd - + @echo -e "TTCN-3 doc generation done..." + @echo -e "Output file is located here: $(outdir)/t3d.out" + +$(outdir) $(bindir): + mkdir -p $@ + +$(bindir)/$(ATS)$(EXE): $(outdir)/../asn1/libItsAsn.a $(gen_objects) $(cc_objects) + g++ -g -O0 -o $@ $(LDFLAGS) $(gen_objects) $(cc_objects) $(outdir)/../asn1/libItsAsn.a $(libs) + +$(gen_objects) :%.o :%.cc + g++ -g -O0 -c $(addprefix -D, $(defines)) $(addprefix -I, $(includes)) -o $@ $< + +$(cc_objects) : $(outdir)/%.o : %.cc + mkdir -p $(dir $@) + g++ -g -O0 -c $(addprefix -D, $(defines)) $(addprefix -I, $(includes)) -o $@ $< + +#$(gen_sources): +# $(TTCN3_DIR)/bin/compiler -n -e -L -R -U none -o $(outdir) $(tt_sources) + +$(gen_sources): $(outdir)/.generate + +$(outdir)/.generate: Makefile $(tt_sources) + $(TTCN3_DIR)/bin/compiler -w -d -e -f -g -l -L -R -U none -x -X -o $(outdir) $(tt_sources) + touch $@ + +$(bindir)/libItsAsn.so: $(outdir)/asn1/libItsAsn.so + cp -f $< $@ + +$(outdir)/../asn1/libItsAsn.a: FORCE + mkdir -p $(outdir)/../asn1 + $(MAKE) -C $(outdir)/../asn1 -f ../../asn1/Makefile + +$(foreach S, $(ttcn_sources), $(eval $(outdir)/$(notdir $(patsubst %.ttcn, %.cc, $(S))): $(S))) +$(foreach S, $(ttcn3_sources), $(eval $(outdir)/$(notdir $(patsubst %.ttcn3, %.cc, $(S))): $(S))) +$(foreach S, $(asn_sources), $(eval $(outdir)/$(notdir $(patsubst %.asn, %.cc, $(S))): $(S))) +$(foreach S, $(asn1_sources), $(eval $(outdir)/$(notdir $(patsubst %.asn1, %.cc, $(S))): $(S))) + diff --git a/asn1/Makefile b/asn1/Makefile index e381ebcfd67c9e9534eb74e4fdfcabdec9925b3d..85ef8783d4dfd6eaf5cbfd87dedbc8c31a3a8bc4 100644 --- a/asn1/Makefile +++ b/asn1/Makefile @@ -1,203 +1,204 @@ -########################################################## -# This Makefile is to build the ASN1 library to be used -# for external codec in Titan -# This Makefile is expected that asn1c compiler is -# installed in the PATHs -########################################################## - -# The name of the library -ASN_LIBRARY = libItsAsn.a -# ASN.1 files to be included in the library -ASN_FILES = AtsCAM/lib_cam_bases/asn1/CAM_PDU_Descriptions.asn \ - AtsCAM/lib_cam_bases/asn1/cdd/ITS_Container.asn \ - AtsDENM/lib/asn1/DENM_PDU_Descriptions.asn \ - AtsSecurity/lib/asn1/EtsiTs103097ExtensionModule.asn \ - AtsSecurity/lib/asn1/EtsiTs103097Module.asn \ - AtsSecurity/lib/asn1/ieee1609dot2/Ieee1609Dot2.asn \ - AtsSecurity/lib/asn1/ieee1609dot2/Ieee1609Dot2BaseTypes.asn\ - AtsIS/lib/asn1/IVIM_PDU_Descriptions.asn \ - AtsIS/lib/asn1/MAPEM_PDU_Descriptions.asn \ - AtsIS/lib/asn1/RTCMEM_PDU_Descriptions.asn \ - AtsIS/lib/asn1/SPATEM_PDU_Descriptions.asn \ - AtsIS/lib/asn1/SREM_PDU_Descriptions.asn \ - AtsIS/lib/asn1/SSEM_PDU_Descriptions.asn \ - AtsIS/lib/asn1/iso-patched/EfcDsrcApplication.asn \ - AtsIS/lib/asn1/iso-patched/EfcDsrcGeneric.asn \ - AtsIS/lib/asn1/iso-patched/ElectronicRegistrationIdentificationVehicleDataModule.asn \ - AtsIS/lib/asn1/iso-patched/GDD.asn \ - AtsIS/lib/asn1/iso-patched/DSRC.asn \ - AtsIS/lib/asn1/iso-patched/DSRC_noCircular.asn \ - AtsIS/lib/asn1/iso-patched/REGION.asn \ - AtsIS/lib/asn1/iso-patched/AddGrpC.asn \ - ../build/asn1/ISO_TS_14816/AVIAEINumberingAndDataStructures.asn \ - ../build/asn1/ISO_TS_17419/CITSapplMgmtIDs.asn \ - ../build/asn1/ISO_TS_19321/IVI.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Crl.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2CrlBaseTypes.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaEeInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaLaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaMaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaRaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1Acpc.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1CamRaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1CertManagement.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1EcaEeInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1EeMaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1EeRaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1LaMaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1LaRaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1MaRaInterface.asn \ - AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1Protocol.asn - -# ../build/asn1/ISO_TS_19091/ISO-TS-19091-addgrp-C-2018-patched.asn \ -# ../build/asn1/ISO_TS_19091/AddGrpC.asn \ -# ../build/asn1/ISO_TS_19091/AddGrpC_noCircular.asn \ -# ../build/asn1/ISO_TS_19091/DSRC.asn \ -# ../build/asn1/ISO_TS_19091/DSRC_REGION_noCircular.asn \ -# ../build/asn1/ISO_TS_19091/REGION.asn \ - -# AtsPki/lib/asn1/EtsiTs102941BaseTypes.asn \ -# AtsPki/lib/asn1/EtsiTs102941MessagesCa.asn \ -# AtsPki/lib/asn1/EtsiTs102941TrustLists.asn \ -# AtsPki/lib/asn1/EtsiTs102941TypesAuthorization.asn \ -# AtsPki/lib/asn1/EtsiTs102941TypesAuthorizationValidation.asn \ -# AtsPki/lib/asn1/EtsiTs102941TypesCaManagement.asn \ -# AtsPki/lib/asn1/EtsiTs102941TypesEnrolment.asn \ -# AtsPki/lib/asn1/EtsiTs102941TypesLinkCertificate.asn \ - -# PDUs -PDU = CAM DENM MAPEM SPATEM SREM SSEM IVIM RTCMEM EtsiTs103097Data EtsiTs103097Certificate -#EtsiTs102941Data - -#patches -PATCHES = PsidGroupPermissions.c.diff - -ASN1C:=asn1c -#Override ASN1C instalation path -#ASN1C_PATH = - -ifneq (, $(ASN1C_PATH)) -# OS=$(shell uname) - ifneq (Windows_NT,$(OS)) - ASN1C:=$(ASN1C_PATH)/asn1c/asn1c -S $(ASN1C_PATH)/skeletons - else - ASN1C:=$(ASN1C_PATH)/asn1c/asn1c.exe -S $(ASN1C_PATH)/skeletons - endif -endif - -ifeq (,$(ASN_DIR)) -########################################################## -# Build path for the library -BIN_DIR := . -SCRIPT_DIR := $(dir $(lastword $(MAKEFILE_LIST))) -ASN_DIR := $(dir $(SCRIPT_DIR))../ttcn - -.PHONY: FORCE - -all: $(BIN_DIR)/$(ASN_LIBRARY) -clean: - rm -rf $(BIN_DIR) - -$(BIN_DIR)/$(ASN_LIBRARY): $(BIN_DIR)/Makefile - make -C $(BIN_DIR) all - -$(BIN_DIR): - mkdir -p $@ - -$(BIN_DIR)/Makefile: $(BIN_DIR) $(SCRIPT_DIR)/Makefile - echo SCRIPT_DIR=$(SCRIPT_DIR) > $@ - echo ASN_DIR=$(ASN_DIR) >>$@ - cat $(SCRIPT_DIR)/Makefile >>$@ - -########################################################## -else -########################################################## -# This part is executed within the BIN_DIR directory to -# override variables from the Makefile.am.libasncodec -# generated by asn1c -LIB_MAKEFILE=Makefile.am.libasncodec -include $(LIB_MAKEFILE) -OBJS = ${ASN_MODULE_SRCS:.c=.o} -CONVERTER=converter -ASN_CONVERTER_SOURCES := \ - converter-example.c\ - pdu_collection.c -CONVERTER_OBJS=${ASN_CONVERTER_SOURCES:.c=.o} -CFLAGS += $(ASN_MODULE_CFLAGS) -DPDU=CAM -DASN_PDU_COLLECTION -fPIC -I. - -all: Makefile $(ASN_LIBRARY) - -$(LIB_MAKEFILE): $(addprefix $(ASN_DIR)/, $(ASN_FILES)) - $(ASN1C) -no-gen-example $(addprefix -pdu=,$(PDU)) -fcompound-names $^ - -for n in $(PATCHES); do git apply "$(SCRIPT_DIR)/$$n"; done - -$(CONVERTER): $(ASN_LIBRARY) $(CONVERTER_OBJS) - $(CC) $(CFLAGS) -o $@ $(CONVERTER_OBJS) $(ASN_LIBRARY) $(LIBS) - -$(ASN_LIBRARY): ${ASN_MODULE_SRCS:.c=.o} - ar rcs $@ $^ -# $(CC) $(CFLAGS) -o $@ $^ -shared $(LDFLAGS) $(LIBS) - -.SUFFIXES: -.SUFFIXES: .c .o - -.c.o: - $(CC) $(CFLAGS) -o $@ -c $< - -clean: - rm -f $(CONVERTER) $(ASN_LIBRARY) - rm -f $(OBJS) $(CONVERTER_OBJS) - -regen: clear-asn1c $(LIB_MAKEFILE) -clear-asn1c: - rm -f $(LIB_MAKEFILE) - -Makefile: $(SCRIPT_DIR)/Makefile - echo SCRIPT_DIR=$(SCRIPT_DIR) > $@ - echo ASN_DIR=$(ASN_DIR) >>$@ - cat $< >>$@ -########################################################## - -$(ASN_DIR)/../build/asn1/ISO_TS_14816/AVIAEINumberingAndDataStructures.asn: $(ASN_DIR)/../build/asn1/ISO_TS_14816 - curl 'https://standards.iso.org/iso/14816/ISO14816%20ASN.1%20repository/ISO14816_AVIAEINumberingAndDataStructures.asn' | \ - sed -e 's/IssuerIdentifier/AVIAEIIssuerIdentifier/g' > "$@" - -#../build/asn1/ISO_TS_14906/EfcDsrcApplication.asn: $(ASN_DIR)/../build/asn1/ISO_TS_14906 -# curl -o "$@" 'https://standards.iso.org/iso/14906/ed-3/en/ISO14906(2018)EfcDsrcApplicationv6.asn' - -#../build/asn1/ISO_TS_14906/EfcDsrcGeneric.asn: $(ASN_DIR)/../build/asn1/ISO_TS_14906 -# curl -o "$@" 'https://standards.iso.org/iso/14906/ed-3/en/ISO14906(2018)EfcDsrcGenericv7.asn' - -$(ASN_DIR)/../build/asn1/ISO_TS_17419/CITSapplMgmtIDs.asn: $(ASN_DIR)/../build/asn1/ISO_TS_17419 - curl -o "$@" 'https://standards.iso.org/iso/ts/17419/TS%2017419%20ASN.1%20repository/TS17419_2014_CITSapplMgmtIDs.asn' - -$(ASN_DIR)/../build/asn1/ISO_TS_19091/ISO-TS-19091-addgrp-C-2018-patched.asn: $(ASN_DIR)/../build/asn1/ISO_TS_19091 - curl 'https://standards.iso.org/iso/ts/19091/ed-2/en/ISO-TS-19091-addgrp-C-2018.asn' | \ - sed -e 's/\bHeadingConfidence\b/HeadingConfidenceDSRC/g' \ - -e 's/\bSpeedConfidence\b/SpeedConfidenceDSRC/g' \ - -e 's/\bHeading\b/HeadingDSRC/g' > "$@" - -$(ASN_DIR)/../build/asn1/ISO_TS_17419/CITSdataDictionary1.asn: $(ASN_DIR)/../build/asn1/ISO_TS_17419 - curl -o "$@" 'https://standards.iso.org/iso/17419/ed-1/en/17419.1.asn' - -$(ASN_DIR)/../build/asn1/ISO_TS_17419/CITSdataDictionary2.asn: $(ASN_DIR)/../build/asn1/ISO_TS_17419 - curl -o "$@" 'https://standards.iso.org/iso/17419/ed-1/en/17419.2.asn' - -#../build/asn1/ISO_TS_19091/AddGrpC.asn: -#../build/asn1/ISO_TS_19091/AddGrpC_noCircular.asn: -#../build/asn1/ISO_TS_19091/DSRC.asn: -#../build/asn1/ISO_TS_19091/DSRC_REGION_noCircular.asn -#../build/asn1/ISO_TS_19091/REGION.asn - -$(ASN_DIR)/../build/asn1/ISO_TS_19321/IVI.asn: $(ASN_DIR)/../build/asn1/ISO_TS_19321 - curl 'https://standards.iso.org/iso/ts/19321/ed-2/en/ISO19321IVIv2.asn' | sed -s 's/\bCITSdataDictionary1\b/CITSapplMgmtIDs/g' > "$@" - - -#../build/asn1/ISO_TS_24534-3/ElectronicRegistrationIdentificationVehicleDataModule.asn: ../build/asn1/ISO_TS_24534-3 -# curl -o "$@" 'https://standards.iso.org/iso/24534/-3/ISO%2024534-3%20ASN.1%20repository/ISO24534-3_ElectronicRegistrationIdentificationVehicleDataModule_ForBallot.asn' - - -$(addprefix $(ASN_DIR)/, ../build/asn1/ISO_TS_24534-3 ../build/asn1/ISO_TS_19321 ../build/asn1/ISO_TS_19091 ../build/asn1/ISO_TS_17419 ../build/asn1/ISO_TS_14906 ../build/asn1/ISO_TS_14816): - mkdir -p "$@" - -endif +########################################################## +# This Makefile is to build the ASN1 library to be used +# for external codec in Titan +# This Makefile is expected that asn1c compiler is +# installed in the PATHs +########################################################## + +# The name of the library +ASN_LIBRARY = libItsAsn.a +# ASN.1 files to be included in the library +ASN_FILES = AtsCAM/lib_cam_bases/asn1/CAM_PDU_Descriptions.asn \ + AtsCAM/lib_cam_bases/asn1/cdd/ITS_Container.asn \ + AtsDENM/lib/asn1/DENM_PDU_Descriptions.asn \ + AtsSecurity/lib/asn1/EtsiTs103097ExtensionModule.asn \ + AtsSecurity/lib/asn1/EtsiTs103097Module.asn \ + AtsSecurity/lib/asn1/ieee1609dot2/Ieee1609Dot2.asn \ + AtsSecurity/lib/asn1/ieee1609dot2/Ieee1609Dot2BaseTypes.asn\ + AtsIS/lib/asn1/IVIM_PDU_Descriptions.asn \ + AtsIS/lib/asn1/MAPEM_PDU_Descriptions.asn \ + AtsIS/lib/asn1/RTCMEM_PDU_Descriptions.asn \ + AtsIS/lib/asn1/SPATEM_PDU_Descriptions.asn \ + AtsIS/lib/asn1/SREM_PDU_Descriptions.asn \ + AtsIS/lib/asn1/SSEM_PDU_Descriptions.asn \ + AtsIS/lib/asn1/iso-patched/EfcDsrcApplication.asn \ + AtsIS/lib/asn1/iso-patched/EfcDsrcGeneric.asn \ + AtsIS/lib/asn1/iso-patched/ElectronicRegistrationIdentificationVehicleDataModule.asn \ + AtsIS/lib/asn1/iso-patched/GDD.asn \ + AtsIS/lib/asn1/iso-patched/DSRC.asn \ + AtsIS/lib/asn1/iso-patched/DSRC_noCircular.asn \ + AtsIS/lib/asn1/iso-patched/REGION.asn \ + AtsIS/lib/asn1/iso-patched/AddGrpC.asn \ + AtsIS/lib/asn1/iso-patched/AddGrpC_noCircular.asn \ + ../build/asn1/ISO_TS_14816/AVIAEINumberingAndDataStructures.asn \ + ../build/asn1/ISO_TS_17419/CITSapplMgmtIDs.asn \ + ../build/asn1/ISO_TS_19321/IVI.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Crl.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2CrlBaseTypes.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaEeInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaLaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaMaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1AcaRaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1Acpc.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1CamRaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1CertManagement.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1EcaEeInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1EeMaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1EeRaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1LaMaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1LaRaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1MaRaInterface.asn \ + AtsPki/lib/asn1/ieee_1609.2.1/Ieee1609Dot2Dot1Protocol.asn + +# ../build/asn1/ISO_TS_19091/ISO-TS-19091-addgrp-C-2018-patched.asn \ +# ../build/asn1/ISO_TS_19091/AddGrpC.asn \ +# ../build/asn1/ISO_TS_19091/AddGrpC_noCircular.asn \ +# ../build/asn1/ISO_TS_19091/DSRC.asn \ +# ../build/asn1/ISO_TS_19091/DSRC_REGION_noCircular.asn \ +# ../build/asn1/ISO_TS_19091/REGION.asn \ + +# AtsPki/lib/asn1/EtsiTs102941BaseTypes.asn \ +# AtsPki/lib/asn1/EtsiTs102941MessagesCa.asn \ +# AtsPki/lib/asn1/EtsiTs102941TrustLists.asn \ +# AtsPki/lib/asn1/EtsiTs102941TypesAuthorization.asn \ +# AtsPki/lib/asn1/EtsiTs102941TypesAuthorizationValidation.asn \ +# AtsPki/lib/asn1/EtsiTs102941TypesCaManagement.asn \ +# AtsPki/lib/asn1/EtsiTs102941TypesEnrolment.asn \ +# AtsPki/lib/asn1/EtsiTs102941TypesLinkCertificate.asn \ + +# PDUs +PDU = CAM DENM MAPEM SPATEM SREM SSEM IVIM RTCMEM EtsiTs103097Data EtsiTs103097Certificate +#EtsiTs102941Data + +#patches +PATCHES = PsidGroupPermissions.c.diff + +ASN1C:=asn1c +#Override ASN1C instalation path +#ASN1C_PATH = + +ifneq (, $(ASN1C_PATH)) +# OS=$(shell uname) + ifneq (Windows_NT,$(OS)) + ASN1C:=$(ASN1C_PATH)/asn1c/asn1c -S $(ASN1C_PATH)/skeletons + else + ASN1C:=$(ASN1C_PATH)/asn1c/asn1c.exe -S $(ASN1C_PATH)/skeletons + endif +endif + +ifeq (,$(ASN_DIR)) +########################################################## +# Build path for the library +BIN_DIR := . +SCRIPT_DIR := $(dir $(lastword $(MAKEFILE_LIST))) +ASN_DIR := $(dir $(SCRIPT_DIR))../ttcn + +.PHONY: FORCE + +all: $(BIN_DIR)/$(ASN_LIBRARY) +clean: + rm -rf $(BIN_DIR) + +$(BIN_DIR)/$(ASN_LIBRARY): $(BIN_DIR)/Makefile + make -C $(BIN_DIR) all + +$(BIN_DIR): + mkdir -p $@ + +$(BIN_DIR)/Makefile: $(BIN_DIR) $(SCRIPT_DIR)/Makefile + echo SCRIPT_DIR=$(SCRIPT_DIR) > $@ + echo ASN_DIR=$(ASN_DIR) >>$@ + cat $(SCRIPT_DIR)/Makefile >>$@ + +########################################################## +else +########################################################## +# This part is executed within the BIN_DIR directory to +# override variables from the Makefile.am.libasncodec +# generated by asn1c +LIB_MAKEFILE=Makefile.am.libasncodec +include $(LIB_MAKEFILE) +OBJS = ${ASN_MODULE_SRCS:.c=.o} +CONVERTER=converter +ASN_CONVERTER_SOURCES := \ + converter-example.c\ + pdu_collection.c +CONVERTER_OBJS=${ASN_CONVERTER_SOURCES:.c=.o} +CFLAGS += $(ASN_MODULE_CFLAGS) -DPDU=CAM -DASN_PDU_COLLECTION -fPIC -I. + +all: Makefile $(ASN_LIBRARY) + +$(LIB_MAKEFILE): $(addprefix $(ASN_DIR)/, $(ASN_FILES)) + $(ASN1C) -no-gen-example $(addprefix -pdu=,$(PDU)) -fcompound-names $^ + -for n in $(PATCHES); do git apply "$(SCRIPT_DIR)/$$n"; done + +$(CONVERTER): $(ASN_LIBRARY) $(CONVERTER_OBJS) + $(CC) $(CFLAGS) -o $@ $(CONVERTER_OBJS) $(ASN_LIBRARY) $(LIBS) + +$(ASN_LIBRARY): ${ASN_MODULE_SRCS:.c=.o} + ar rcs $@ $^ +# $(CC) $(CFLAGS) -o $@ $^ -shared $(LDFLAGS) $(LIBS) + +.SUFFIXES: +.SUFFIXES: .c .o + +.c.o: + $(CC) $(CFLAGS) -o $@ -c $< + +clean: + rm -f $(CONVERTER) $(ASN_LIBRARY) + rm -f $(OBJS) $(CONVERTER_OBJS) + +regen: clear-asn1c $(LIB_MAKEFILE) +clear-asn1c: + rm -f $(LIB_MAKEFILE) + +Makefile: $(SCRIPT_DIR)/Makefile + echo SCRIPT_DIR=$(SCRIPT_DIR) > $@ + echo ASN_DIR=$(ASN_DIR) >>$@ + cat $< >>$@ +########################################################## + +$(ASN_DIR)/../build/asn1/ISO_TS_14816/AVIAEINumberingAndDataStructures.asn: $(ASN_DIR)/../build/asn1/ISO_TS_14816 + curl 'https://standards.iso.org/iso/14816/ISO14816%20ASN.1%20repository/ISO14816_AVIAEINumberingAndDataStructures.asn' | \ + sed -e 's/IssuerIdentifier/AVIAEIIssuerIdentifier/g' > "$@" + +#../build/asn1/ISO_TS_14906/EfcDsrcApplication.asn: $(ASN_DIR)/../build/asn1/ISO_TS_14906 +# curl -o "$@" 'https://standards.iso.org/iso/14906/ed-3/en/ISO14906(2018)EfcDsrcApplicationv6.asn' + +#../build/asn1/ISO_TS_14906/EfcDsrcGeneric.asn: $(ASN_DIR)/../build/asn1/ISO_TS_14906 +# curl -o "$@" 'https://standards.iso.org/iso/14906/ed-3/en/ISO14906(2018)EfcDsrcGenericv7.asn' + +$(ASN_DIR)/../build/asn1/ISO_TS_17419/CITSapplMgmtIDs.asn: $(ASN_DIR)/../build/asn1/ISO_TS_17419 + curl -o "$@" 'https://standards.iso.org/iso/ts/17419/TS%2017419%20ASN.1%20repository/TS17419_2014_CITSapplMgmtIDs.asn' + +$(ASN_DIR)/../build/asn1/ISO_TS_19091/ISO-TS-19091-addgrp-C-2018-patched.asn: $(ASN_DIR)/../build/asn1/ISO_TS_19091 + curl 'https://standards.iso.org/iso/ts/19091/ed-2/en/ISO-TS-19091-addgrp-C-2018.asn' | \ + sed -e 's/\bHeadingConfidence\b/HeadingConfidenceDSRC/g' \ + -e 's/\bSpeedConfidence\b/SpeedConfidenceDSRC/g' \ + -e 's/\bHeading\b/HeadingDSRC/g' > "$@" + +$(ASN_DIR)/../build/asn1/ISO_TS_17419/CITSdataDictionary1.asn: $(ASN_DIR)/../build/asn1/ISO_TS_17419 + curl -o "$@" 'https://standards.iso.org/iso/17419/ed-1/en/17419.1.asn' + +$(ASN_DIR)/../build/asn1/ISO_TS_17419/CITSdataDictionary2.asn: $(ASN_DIR)/../build/asn1/ISO_TS_17419 + curl -o "$@" 'https://standards.iso.org/iso/17419/ed-1/en/17419.2.asn' + +#../build/asn1/ISO_TS_19091/AddGrpC.asn: +#../build/asn1/ISO_TS_19091/AddGrpC_noCircular.asn: +#../build/asn1/ISO_TS_19091/DSRC.asn: +#../build/asn1/ISO_TS_19091/DSRC_REGION_noCircular.asn +#../build/asn1/ISO_TS_19091/REGION.asn + +$(ASN_DIR)/../build/asn1/ISO_TS_19321/IVI.asn: $(ASN_DIR)/../build/asn1/ISO_TS_19321 + curl 'https://standards.iso.org/iso/ts/19321/ed-2/en/ISO19321IVIv2.asn' | sed -s 's/\bCITSdataDictionary1\b/CITSapplMgmtIDs/g' > "$@" + + +#../build/asn1/ISO_TS_24534-3/ElectronicRegistrationIdentificationVehicleDataModule.asn: ../build/asn1/ISO_TS_24534-3 +# curl -o "$@" 'https://standards.iso.org/iso/24534/-3/ISO%2024534-3%20ASN.1%20repository/ISO24534-3_ElectronicRegistrationIdentificationVehicleDataModule_ForBallot.asn' + + +$(addprefix $(ASN_DIR)/, ../build/asn1/ISO_TS_24534-3 ../build/asn1/ISO_TS_19321 ../build/asn1/ISO_TS_19091 ../build/asn1/ISO_TS_17419 ../build/asn1/ISO_TS_14906 ../build/asn1/ISO_TS_14816): + mkdir -p "$@" + +endif diff --git a/asn1/PsidGroupPermissions.c.diff b/asn1/PsidGroupPermissions.c.diff index 54700d7270325253c99dc05f5c6de87c94d0a36b..c684a0a478f17bca478225d961496eddf52e2b53 100755 --- a/asn1/PsidGroupPermissions.c.diff +++ b/asn1/PsidGroupPermissions.c.diff @@ -1,35 +1,35 @@ ---- PsidGroupPermissions.c-orig 2018-08-23 15:50:25.762030100 +0200 -+++ PsidGroupPermissions.c 2018-09-10 16:47:19.921571200 +0200 -@@ -51,6 +51,22 @@ - *st = 0; - return 0; - } -+static int asn_DFL_5_cmp_0(const void *sptr) { -+ uint8_t def_buf[] = { 0 }; -+ BIT_STRING_t def = { &def_buf[0], 1, 7 }; -+ return BIT_STRING_compare(&asn_DEF_EndEntityType, sptr, &def); -+} -+ -+static int asn_DFL_5_set_0(void **sptr) { -+ BIT_STRING_t * st = *(BIT_STRING_t **)sptr; -+ if (!st) { -+ st = (*sptr = CALLOC(1, sizeof(*st))); -+ if (!st) return -1; -+ } -+ OCTET_STRING_fromBuf((OCTET_STRING_t *)st, "\x0", 1); -+ return 0; -+} -+ - asn_TYPE_member_t asn_MBR_PsidGroupPermissions_1[] = { - { ATF_NOFLAGS, 0, offsetof(struct PsidGroupPermissions, subjectPermissions), - (ASN_TAG_CLASS_CONTEXT | (0 << 2)), -@@ -87,7 +103,8 @@ - &asn_DEF_EndEntityType, - 0, - { 0, 0, 0 }, -- 0, 0, /* No default value */ -+ asn_DFL_5_cmp_0, -+ asn_DFL_5_set_0, - "eeType" - }, - }; +--- PsidGroupPermissions.c-orig 2018-08-23 15:50:25.762030100 +0200 ++++ PsidGroupPermissions.c 2018-09-10 16:47:19.921571200 +0200 +@@ -51,6 +51,22 @@ + *st = 0; + return 0; + } ++static int asn_DFL_5_cmp_0(const void *sptr) { ++ uint8_t def_buf[] = { 0 }; ++ BIT_STRING_t def = { &def_buf[0], 1, 7 }; ++ return BIT_STRING_compare(&asn_DEF_EndEntityType, sptr, &def); ++} ++ ++static int asn_DFL_5_set_0(void **sptr) { ++ BIT_STRING_t * st = *(BIT_STRING_t **)sptr; ++ if (!st) { ++ st = (*sptr = CALLOC(1, sizeof(*st))); ++ if (!st) return -1; ++ } ++ OCTET_STRING_fromBuf((OCTET_STRING_t *)st, "\x0", 1); ++ return 0; ++} ++ + asn_TYPE_member_t asn_MBR_PsidGroupPermissions_1[] = { + { ATF_NOFLAGS, 0, offsetof(struct PsidGroupPermissions, subjectPermissions), + (ASN_TAG_CLASS_CONTEXT | (0 << 2)), +@@ -87,7 +103,8 @@ + &asn_DEF_EndEntityType, + 0, + { 0, 0, 0 }, +- 0, 0, /* No default value */ ++ asn_DFL_5_cmp_0, ++ asn_DFL_5_set_0, + "eeType" + }, + }; diff --git a/ccsrc/Asn1c/asn1_recode_per.cc b/ccsrc/Asn1c/asn1_recode_per.cc index 5259e44101ec304adc23de7c0a7b159f91db6415..543742b9955bea2a43cc679e7501bd71cc4ad1f8 100644 --- a/ccsrc/Asn1c/asn1_recode_per.cc +++ b/ccsrc/Asn1c/asn1_recode_per.cc @@ -1,45 +1,45 @@ -#include - -#include "asn1_recode_per.hh" - -#include - -extern "C" { -static int asn1c_collect_encoded_data(const void *buffer, size_t size, void *application_specific_key) { - TTCN_Buffer *tb = (TTCN_Buffer *)application_specific_key; - tb->put_s(size, (unsigned char *)buffer); - return 0; -} -} - -int asn1_recode_per::recode(const asn_TYPE_descriptor_s &td, int from, int to, TTCN_Buffer &buf) { - int rc = -1; - void * ptr = NULL; - asn_dec_rval_t rc_d; - rc_d = asn_decode(NULL, (asn_transfer_syntax)from, (asn_TYPE_descriptor_s *)&td, &ptr, buf.get_data(), buf.get_len()); - if (rc_d.code == RC_OK) { - // Encode as PER - asn_enc_rval_t rc_e; - buf.clear(); - rc_e = asn_encode(NULL, (asn_transfer_syntax)to, (asn_TYPE_descriptor_s *)&td, ptr, asn1c_collect_encoded_data, &buf); - rc = rc_e.encoded; - } - if (ptr) { - ASN_STRUCT_FREE(td, ptr); - } - return rc; -} - -int asn1_recode_per::ber2per(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf) { return recode(td, (int)ATS_BER, (int)ATS_UNALIGNED_CANONICAL_PER, buf); } - -int asn1_recode_per::per2ber(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf) { return recode(td, (int)ATS_UNALIGNED_BASIC_PER, (int)ATS_DER, buf); } - -/*int asn1_recode_oer::ber2oer(const asn_TYPE_descriptor_s & td, TTCN_Buffer & buf) -{ - return recode(td, (int)ATS_XER, (int)ATS_CANONICAL_OER, buf); -} - -int asn1_recode_oer::oer2ber(const asn_TYPE_descriptor_s & td, TTCN_Buffer & buf) -{ - return recodeOer(td, (int)ATS_BASIC_OER, (int)ATS_XER, buf); - }*/ +#include + +#include "asn1_recode_per.hh" + +#include + +extern "C" { +static int asn1c_collect_encoded_data(const void *buffer, size_t size, void *application_specific_key) { + TTCN_Buffer *tb = (TTCN_Buffer *)application_specific_key; + tb->put_s(size, (unsigned char *)buffer); + return 0; +} +} + +int asn1_recode_per::recode(const asn_TYPE_descriptor_s &td, int from, int to, TTCN_Buffer &buf) { + int rc = -1; + void * ptr = NULL; + asn_dec_rval_t rc_d; + rc_d = asn_decode(NULL, (asn_transfer_syntax)from, (asn_TYPE_descriptor_s *)&td, &ptr, buf.get_data(), buf.get_len()); + if (rc_d.code == RC_OK) { + // Encode as PER + asn_enc_rval_t rc_e; + buf.clear(); + rc_e = asn_encode(NULL, (asn_transfer_syntax)to, (asn_TYPE_descriptor_s *)&td, ptr, asn1c_collect_encoded_data, &buf); + rc = rc_e.encoded; + } + if (ptr) { + ASN_STRUCT_FREE(td, ptr); + } + return rc; +} + +int asn1_recode_per::ber2per(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf) { return recode(td, (int)ATS_BER, (int)ATS_UNALIGNED_CANONICAL_PER, buf); } + +int asn1_recode_per::per2ber(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf) { return recode(td, (int)ATS_UNALIGNED_BASIC_PER, (int)ATS_DER, buf); } + +/*int asn1_recode_oer::ber2oer(const asn_TYPE_descriptor_s & td, TTCN_Buffer & buf) +{ + return recode(td, (int)ATS_XER, (int)ATS_CANONICAL_OER, buf); +} + +int asn1_recode_oer::oer2ber(const asn_TYPE_descriptor_s & td, TTCN_Buffer & buf) +{ + return recodeOer(td, (int)ATS_BASIC_OER, (int)ATS_XER, buf); + }*/ diff --git a/ccsrc/Asn1c/asn1_recode_per.hh b/ccsrc/Asn1c/asn1_recode_per.hh index b5ac27546ca2567145b4f77c35d174ef0b10197f..088a10844d6fe227f8fbbf3b25f27d250ee2c50c 100644 --- a/ccsrc/Asn1c/asn1_recode_per.hh +++ b/ccsrc/Asn1c/asn1_recode_per.hh @@ -1,27 +1,27 @@ -/*! - * \file asn1_recode_per.hh - * \brief Header file ASN.1 PER codec based on asn1c external tool. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -class OCTETSTRING; //! Forward declaration of TITAN class -class CHARSTRING; //! Forward declaration of TITAN class -class BITSTRING; //! Forward declaration of TITAN class -class TTCN_Buffer; //! Forward declaration of TITAN class -class TTCN_EncDec; //! Forward declaration of TITAN class -class TTCN_Typedescriptor_t; //! Forward declaration of TITAN class - -struct asn_TYPE_descriptor_s; //! Forward declaration of asn1c class - -class asn1_recode_per { -protected: - int ber2per(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); - int per2ber(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); - int recode(const asn_TYPE_descriptor_s &td, int from, int to, TTCN_Buffer &buf); -}; // End of class asn1_recode_per +/*! + * \file asn1_recode_per.hh + * \brief Header file ASN.1 PER codec based on asn1c external tool. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +class OCTETSTRING; //! Forward declaration of TITAN class +class CHARSTRING; //! Forward declaration of TITAN class +class BITSTRING; //! Forward declaration of TITAN class +class TTCN_Buffer; //! Forward declaration of TITAN class +class TTCN_EncDec; //! Forward declaration of TITAN class +class TTCN_Typedescriptor_t; //! Forward declaration of TITAN class + +struct asn_TYPE_descriptor_s; //! Forward declaration of asn1c class + +class asn1_recode_per { +protected: + int ber2per(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); + int per2ber(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); + int recode(const asn_TYPE_descriptor_s &td, int from, int to, TTCN_Buffer &buf); +}; // End of class asn1_recode_per diff --git a/ccsrc/Asn1c/module.mk b/ccsrc/Asn1c/module.mk index d15673be1afa116ccd6f0375dda6cbfdf0b163e5..055195feb9fafe139c62ccecc3bc1da1600335c6 100644 --- a/ccsrc/Asn1c/module.mk +++ b/ccsrc/Asn1c/module.mk @@ -1,3 +1,3 @@ -sources := asn1_recode_per.cc -includes := . - +sources := asn1_recode_per.cc +includes := . + diff --git a/ccsrc/EncDec/LibItsBtp_Encdec.cc b/ccsrc/EncDec/LibItsBtp_Encdec.cc index 23bd1b12955c7baf164e80980f544fc57b0ae025..89822c0553c32dbd2be0e76b61c2cfd5628e29a8 100644 --- a/ccsrc/EncDec/LibItsBtp_Encdec.cc +++ b/ccsrc/EncDec/LibItsBtp_Encdec.cc @@ -1,120 +1,120 @@ -#include "LibItsBtp_EncdecDeclarations.hh" - -#include "btp_codec.hh" -#include "loggers.hh" - -namespace LibItsBtp__EncdecDeclarations { - - /**************************************************** - * @desc External function to encode a BtpReq type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__BtpReq(LibItsBtp__TestSystem::BtpReq const &p_btpReq) { - loggers::get_instance().log_msg(">>> fx__enc__BtpReq: ", p_btpReq); - - btp_codec codec; - OCTETSTRING os; - if (codec.encode(p_btpReq.msgOut(), os) == -1) { - loggers::get_instance().warning("fx__enc__BtpReq: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a BtpReq type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__BtpReq(BITSTRING &b, LibItsBtp__TestSystem::BtpReq &p) { - loggers::get_instance().log(">>> fx__dec__BtpReq"); - btp_codec codec; - LibItsBtp__TypesAndValues::BtpPacket pdu; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(is, pdu) == -1) { - loggers::get_instance().warning("fx__dec__BtpReq: -1 result code was returned"); - return -1; - } - p.msgOut() = pdu; - - return 0; - } - - /**************************************************** - * @desc External function to encode a BtpInd type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__BtpInd(LibItsBtp__TestSystem::BtpInd const &p_btpInd) { - loggers::get_instance().log_msg(">>> fx__enc__BtpInd: ", p_btpInd); - - btp_codec codec; - OCTETSTRING os; - if (codec.encode(p_btpInd.msgIn(), os) == -1) { - loggers::get_instance().warning("fx__enc__BtpInd: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a BtpInd type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__BtpInd(BITSTRING &b, LibItsBtp__TestSystem::BtpInd &p_btpInd) { - loggers::get_instance().log(">>> fx__dec__BtpInd"); - btp_codec codec; - LibItsBtp__TypesAndValues::BtpPacket pdu; - OCTETSTRING is = bit2oct(b); - - // Calculate the size of the lower layers information - if (codec.decode(is, pdu) == -1) { - loggers::get_instance().warning("fx__dec__BtpInd: -1 result code was returned"); - return -1; - } - p_btpInd.msgIn() = pdu; - - loggers::get_instance().log_msg("<<< fx__dec__BtpInd: ", p_btpInd); - return 0; - } - - /**************************************************** - * @desc External function to encode a BtpPacket type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__BtpPacket(LibItsBtp__TypesAndValues::BtpPacket const &p_btpPacket) { - loggers::get_instance().log_msg(">>> fx__enc__BtpPacket: ", p_btpPacket); - - btp_codec codec; - OCTETSTRING os; - codec.encode(p_btpPacket, os); - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a BtpPacket type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__BtpPacket(BITSTRING &b, LibItsBtp__TypesAndValues::BtpPacket &p_btpPacket) { - loggers::get_instance().log(">>> fx__dec__BtpPacket"); - btp_codec codec; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(is, p_btpPacket) == -1) { - loggers::get_instance().warning("fx__dec__BtpPacket: -1 result code was returned"); - return -1; - } - return 0; - } - -} // namespace LibItsBtp__EncdecDeclarations +#include "LibItsBtp_EncdecDeclarations.hh" + +#include "btp_codec.hh" +#include "loggers.hh" + +namespace LibItsBtp__EncdecDeclarations { + + /**************************************************** + * @desc External function to encode a BtpReq type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__BtpReq(LibItsBtp__TypesAndValues::BtpReq const &p_btpReq) { + loggers::get_instance().log_msg(">>> fx__enc__BtpReq: ", p_btpReq); + + btp_codec codec; + OCTETSTRING os; + if (codec.encode(p_btpReq.msgOut(), os) == -1) { + loggers::get_instance().warning("fx__enc__BtpReq: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a BtpReq type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__BtpReq(BITSTRING &b, LibItsBtp__TypesAndValues::BtpReq &p) { + loggers::get_instance().log(">>> fx__dec__BtpReq"); + btp_codec codec; + LibItsBtp__TypesAndValues::BtpPacket pdu; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(is, pdu) == -1) { + loggers::get_instance().warning("fx__dec__BtpReq: -1 result code was returned"); + return -1; + } + p.msgOut() = pdu; + + return 0; + } + + /**************************************************** + * @desc External function to encode a BtpInd type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__BtpInd(LibItsBtp__TypesAndValues::BtpInd const &p_btpInd) { + loggers::get_instance().log_msg(">>> fx__enc__BtpInd: ", p_btpInd); + + btp_codec codec; + OCTETSTRING os; + if (codec.encode(p_btpInd.msgIn(), os) == -1) { + loggers::get_instance().warning("fx__enc__BtpInd: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a BtpInd type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__BtpInd(BITSTRING &b, LibItsBtp__TypesAndValues::BtpInd &p_btpInd) { + loggers::get_instance().log(">>> fx__dec__BtpInd"); + btp_codec codec; + LibItsBtp__TypesAndValues::BtpPacket pdu; + OCTETSTRING is = bit2oct(b); + + // Calculate the size of the lower layers information + if (codec.decode(is, pdu) == -1) { + loggers::get_instance().warning("fx__dec__BtpInd: -1 result code was returned"); + return -1; + } + p_btpInd.msgIn() = pdu; + + loggers::get_instance().log_msg("<<< fx__dec__BtpInd: ", p_btpInd); + return 0; + } + + /**************************************************** + * @desc External function to encode a BtpPacket type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__BtpPacket(LibItsBtp__TypesAndValues::BtpPacket const &p_btpPacket) { + loggers::get_instance().log_msg(">>> fx__enc__BtpPacket: ", p_btpPacket); + + btp_codec codec; + OCTETSTRING os; + codec.encode(p_btpPacket, os); + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a BtpPacket type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__BtpPacket(BITSTRING &b, LibItsBtp__TypesAndValues::BtpPacket &p_btpPacket) { + loggers::get_instance().log(">>> fx__dec__BtpPacket"); + btp_codec codec; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(is, p_btpPacket) == -1) { + loggers::get_instance().warning("fx__dec__BtpPacket: -1 result code was returned"); + return -1; + } + return 0; + } + +} // namespace LibItsBtp__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsCam_Encdec.cc b/ccsrc/EncDec/LibItsCam_Encdec.cc index caeaf62d0c02fd0ea588bc40e5dd8a4f21e8d314..26ed2786ab1bb019ee34cfabb3d599fa57a49ccd 100644 --- a/ccsrc/EncDec/LibItsCam_Encdec.cc +++ b/ccsrc/EncDec/LibItsCam_Encdec.cc @@ -1,253 +1,253 @@ -#include - -#include "LibItsCam_EncdecDeclarations.hh" - -#include "cam_codec.hh" -#include "loggers.hh" -#include "uppertester_cam_codec.hh" - -namespace LibItsCam__EncdecDeclarations { - /**************************************************** - * @desc External function to encode a CamReq type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__CamReq(const LibItsCam__TypesAndValues::CamReq &p_camReq) { - loggers::get_instance().log_msg(">>> fx__enc__CamReq: ", p_camReq); - - cam_codec codec; - OCTETSTRING os; - if (codec.encode(p_camReq.msgOut(), os) == -1) { - loggers::get_instance().warning("fx__enc__CamReq: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a CamReq type - * @param value to encode - * @return encoded value - ****************************************************/ - INTEGER fx__dec__CamReq(BITSTRING &b, LibItsCam__TypesAndValues::CamReq &p) { - loggers::get_instance().log(">>> fx__dec__CamReq"); - - cam_codec codec; - CAM__PDU__Descriptions::CAM cam; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(is, cam) == -1) { - loggers::get_instance().warning("fx__dec__CamReq: -1 result code was returned"); - return -1; - } - p.msgOut() = cam; - - return 0; - } - - INTEGER fx__dec__CamInd(BITSTRING &b, LibItsCam__TypesAndValues::CamInd &p_camInd) { - loggers::get_instance().log(">>> fx__dec__CamInd"); - - cam_codec codec; - CAM__PDU__Descriptions::CAM cam; - OCTETSTRING is = bit2oct(b); - - // Calculate the size of the lower layers information - int s = (LibItsCam__TypesAndValues::CamInd_gnNextHeader_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_gnHeaderType_raw_.fieldlength + - LibItsCam__TypesAndValues::CamInd_gnHeaderSubtype_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_gnLifetime_raw_.fieldlength + - LibItsCam__TypesAndValues::CamInd_gnTrafficClass_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_btpDestinationPort_raw_.fieldlength + - LibItsCam__TypesAndValues::CamInd_btpInfo_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_ssp_raw_.fieldlength + - LibItsCam__TypesAndValues::CamInd_its__aid_raw_.fieldlength) / - 8; - // Decode CA message - if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), cam) == -1) { - loggers::get_instance().warning("fx__dec__CamInd: -1 result code was returned"); - return -1; - } - p_camInd.msgIn() = cam; - // Decode lower layer data - TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnNextHeader_raw_.fieldlength / 8)) { - p_camInd.gnNextHeader().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsCam__TypesAndValues::CamInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.gnNextHeader() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__CAM: gnNextHeader=", p_camInd.gnNextHeader()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnHeaderType_raw_.fieldlength / 8)) { - p_camInd.gnHeaderType().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsCam__TypesAndValues::CamInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.gnHeaderType() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__CAM: gnHeaderType=", p_camInd.gnHeaderType()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnHeaderSubtype_raw_.fieldlength / 8)) { - p_camInd.gnHeaderSubtype().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsCam__TypesAndValues::CamInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.gnHeaderSubtype() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__CAM: gnHeaderSubtype=", p_camInd.gnHeaderSubtype()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnLifetime_raw_.fieldlength / 8)) { - p_camInd.gnLifetime().set_to_omit(); - } else { - INTEGER i; - i.decode(LibItsCam__TypesAndValues::CamInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.gnLifetime() = i; - } - loggers::get_instance().log_msg("fx__dec__CAM: gnLifetime=", p_camInd.gnLifetime()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnTrafficClass_raw_.fieldlength / 8)) { - p_camInd.gnTrafficClass().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsCam__TypesAndValues::CamInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.gnTrafficClass() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__CAM: gnTrafficClass=", p_camInd.gnTrafficClass()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_btpDestinationPort_raw_.fieldlength / 8)) { - p_camInd.btpDestinationPort().set_to_omit(); - } else { - INTEGER i; - i.decode(LibItsCam__TypesAndValues::CamInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.btpDestinationPort() = i; - } - loggers::get_instance().log_msg("fx__dec__CAM: btpDestinationPort=", p_camInd.btpDestinationPort()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_btpInfo_raw_.fieldlength / 8)) { - p_camInd.btpInfo().set_to_omit(); - } else { - INTEGER i; - i.decode(LibItsCam__TypesAndValues::CamInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.btpInfo() = i; - } - loggers::get_instance().log_msg("fx__dec__CAM: btpInfo=", p_camInd.btpInfo()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_ssp_raw_.fieldlength / 8)) { - p_camInd.ssp().set_to_omit(); - } else { - BITSTRING bs; - bs.decode(LibItsCam__TypesAndValues::CamInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.ssp() = bs; - } - loggers::get_instance().log_msg("fx__dec__CAM: ssp=", p_camInd.ssp()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_its__aid_raw_.fieldlength / 8)) { - p_camInd.its__aid().set_to_omit(); - } else { - INTEGER i; - i.decode(LibItsCam__TypesAndValues::CamInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_camInd.its__aid() = i; - } - loggers::get_instance().log_msg("fx__dec__CAM: its_aid=", p_camInd.its__aid()); - loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); - - return 0; - } - - BITSTRING fx__enc__CAM(const CAM__PDU__Descriptions::CAM &p_cam) { - loggers::get_instance().log_msg(">>> fx__enc__CAM: ", p_cam); - - cam_codec codec; - OCTETSTRING os; - codec.encode(p_cam, os); - return oct2bit(os); - } - - INTEGER fx__dec__CAM(BITSTRING &b, CAM__PDU__Descriptions::CAM &p) { - loggers::get_instance().log(">>> fx__dec__CAM"); - cam_codec codec; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(OCTETSTRING(is.lengthof(), static_cast(is)), p) == -1) { - loggers::get_instance().warning("fx__dec__CAM: -1 result code was returned"); - return -1; - } - - return 0; - } - - BITSTRING fx__enc__UtCamInitialize(const LibItsCam__TypesAndValues::UtCamInitialize &p_utCamInitialize) { - loggers::get_instance().log_msg(">>> fx__enc__UtCamInitialize: ", p_utCamInitialize); - - uppertester_cam_codec codec; - OCTETSTRING os; - codec.encode(p_utCamInitialize, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtCamChangePosition(const LibItsCam__TypesAndValues::UtCamChangePosition &p_utCamChangePosition) { - loggers::get_instance().log_msg(">>> fx__enc__UtCamChangePosition: ", p_utCamChangePosition); - - uppertester_cam_codec codec; - OCTETSTRING os; - codec.encode(p_utCamChangePosition, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtCamTrigger(const LibItsCam__TypesAndValues::UtCamTrigger &p_utCamTrigger) { - loggers::get_instance().log_msg(">>> fx__enc__UtCamTrigger: ", p_utCamTrigger); - - uppertester_cam_codec codec; - OCTETSTRING os; - codec.encode(p_utCamTrigger, os); - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a UtCamResults type - * @param value to encode - * @return encoded value - ****************************************************/ - INTEGER fx__dec__UtCamResults(BITSTRING &b, LibItsCam__TypesAndValues::UtCamResults &p) { - loggers::get_instance().log(">>> fx__dec__UtCamResults"); - - uppertester_cam_codec codec; - OCTETSTRING is = bit2oct(b); - std::unique_ptr ptr = codec.decode(is); - if (ptr == nullptr) { - loggers::get_instance().warning("fx__dec__UtCamResults: -1 result code was returned"); - return -1; - } - p = static_cast(*ptr); - return 0; - } - - /**************************************************** - * @desc External function to decode a UtCamEventInd type - * @param value to encode - * @return encoded value - ****************************************************/ - INTEGER fx__dec__UtCamEventInd(BITSTRING &b, LibItsCam__TypesAndValues::UtCamEventInd &p) { - loggers::get_instance().log(">>> fx__dec__UtCamEventInd"); - - uppertester_cam_codec codec; - OCTETSTRING is = bit2oct(b); - std::unique_ptr ptr = codec.decode(is); - if (ptr == nullptr) { - loggers::get_instance().warning("fx__dec__UtCamEventInd: -1 result code was returned"); - return -1; - } - p = static_cast(*ptr); - return 0; - } - -} // namespace LibItsCam__EncdecDeclarations +#include + +#include "LibItsCam_EncdecDeclarations.hh" + +#include "cam_codec.hh" +#include "loggers.hh" +#include "uppertester_cam_codec.hh" + +namespace LibItsCam__EncdecDeclarations { + /**************************************************** + * @desc External function to encode a CamReq type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__CamReq(const LibItsCam__TypesAndValues::CamReq &p_camReq) { + loggers::get_instance().log_msg(">>> fx__enc__CamReq: ", p_camReq); + + cam_codec codec; + OCTETSTRING os; + if (codec.encode(p_camReq.msgOut(), os) == -1) { + loggers::get_instance().warning("fx__enc__CamReq: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a CamReq type + * @param value to encode + * @return encoded value + ****************************************************/ + INTEGER fx__dec__CamReq(BITSTRING &b, LibItsCam__TypesAndValues::CamReq &p) { + loggers::get_instance().log(">>> fx__dec__CamReq"); + + cam_codec codec; + CAM__PDU__Descriptions::CAM cam; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(is, cam) == -1) { + loggers::get_instance().warning("fx__dec__CamReq: -1 result code was returned"); + return -1; + } + p.msgOut() = cam; + + return 0; + } + + INTEGER fx__dec__CamInd(BITSTRING &b, LibItsCam__TypesAndValues::CamInd &p_camInd) { + loggers::get_instance().log(">>> fx__dec__CamInd"); + + cam_codec codec; + CAM__PDU__Descriptions::CAM cam; + OCTETSTRING is = bit2oct(b); + + // Calculate the size of the lower layers information + int s = (LibItsCam__TypesAndValues::CamInd_gnNextHeader_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_gnHeaderType_raw_.fieldlength + + LibItsCam__TypesAndValues::CamInd_gnHeaderSubtype_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_gnLifetime_raw_.fieldlength + + LibItsCam__TypesAndValues::CamInd_gnTrafficClass_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_btpDestinationPort_raw_.fieldlength + + LibItsCam__TypesAndValues::CamInd_btpInfo_raw_.fieldlength + LibItsCam__TypesAndValues::CamInd_ssp_raw_.fieldlength + + LibItsCam__TypesAndValues::CamInd_its__aid_raw_.fieldlength) / + 8; + // Decode CA message + if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), cam) == -1) { + loggers::get_instance().warning("fx__dec__CamInd: -1 result code was returned"); + return -1; + } + p_camInd.msgIn() = cam; + // Decode lower layer data + TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // gnNextHeader + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnNextHeader_raw_.fieldlength / 8)) { + p_camInd.gnNextHeader().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsCam__TypesAndValues::CamInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.gnNextHeader() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__CAM: gnNextHeader=", p_camInd.gnNextHeader()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // gnHeaderType + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnHeaderType_raw_.fieldlength / 8)) { + p_camInd.gnHeaderType().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsCam__TypesAndValues::CamInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.gnHeaderType() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__CAM: gnHeaderType=", p_camInd.gnHeaderType()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // gnHeaderSubtype + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + p_camInd.gnHeaderSubtype().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsCam__TypesAndValues::CamInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.gnHeaderSubtype() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__CAM: gnHeaderSubtype=", p_camInd.gnHeaderSubtype()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // gnLifetime + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnLifetime_raw_.fieldlength / 8)) { + p_camInd.gnLifetime().set_to_omit(); + } else { + INTEGER i; + i.decode(LibItsCam__TypesAndValues::CamInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.gnLifetime() = i; + } + loggers::get_instance().log_msg("fx__dec__CAM: gnLifetime=", p_camInd.gnLifetime()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // gnTrafficClass + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_gnTrafficClass_raw_.fieldlength / 8)) { + p_camInd.gnTrafficClass().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsCam__TypesAndValues::CamInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.gnTrafficClass() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__CAM: gnTrafficClass=", p_camInd.gnTrafficClass()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // btpDestinationPort + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_btpDestinationPort_raw_.fieldlength / 8)) { + p_camInd.btpDestinationPort().set_to_omit(); + } else { + INTEGER i; + i.decode(LibItsCam__TypesAndValues::CamInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.btpDestinationPort() = i; + } + loggers::get_instance().log_msg("fx__dec__CAM: btpDestinationPort=", p_camInd.btpDestinationPort()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // btpInfo + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_btpInfo_raw_.fieldlength / 8)) { + p_camInd.btpInfo().set_to_omit(); + } else { + INTEGER i; + i.decode(LibItsCam__TypesAndValues::CamInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.btpInfo() = i; + } + loggers::get_instance().log_msg("fx__dec__CAM: btpInfo=", p_camInd.btpInfo()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // ssp + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_ssp_raw_.fieldlength / 8)) { + p_camInd.ssp().set_to_omit(); + } else { + BITSTRING bs; + bs.decode(LibItsCam__TypesAndValues::CamInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.ssp() = bs; + } + loggers::get_instance().log_msg("fx__dec__CAM: ssp=", p_camInd.ssp()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + // its__aid + if (decoding_buffer.get_read_len() < static_cast(LibItsCam__TypesAndValues::CamInd_its__aid_raw_.fieldlength / 8)) { + p_camInd.its__aid().set_to_omit(); + } else { + INTEGER i; + i.decode(LibItsCam__TypesAndValues::CamInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_camInd.its__aid() = i; + } + loggers::get_instance().log_msg("fx__dec__CAM: its_aid=", p_camInd.its__aid()); + loggers::get_instance().log_to_hexa("fx__dec__CAM: ", decoding_buffer); + + return 0; + } + + BITSTRING fx__enc__CAM(const CAM__PDU__Descriptions::CAM &p_cam) { + loggers::get_instance().log_msg(">>> fx__enc__CAM: ", p_cam); + + cam_codec codec; + OCTETSTRING os; + codec.encode(p_cam, os); + return oct2bit(os); + } + + INTEGER fx__dec__CAM(BITSTRING &b, CAM__PDU__Descriptions::CAM &p) { + loggers::get_instance().log(">>> fx__dec__CAM"); + cam_codec codec; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(OCTETSTRING(is.lengthof(), static_cast(is)), p) == -1) { + loggers::get_instance().warning("fx__dec__CAM: -1 result code was returned"); + return -1; + } + + return 0; + } + + BITSTRING fx__enc__UtCamInitialize(const LibItsCam__TypesAndValues::UtCamInitialize &p_utCamInitialize) { + loggers::get_instance().log_msg(">>> fx__enc__UtCamInitialize: ", p_utCamInitialize); + + uppertester_cam_codec codec; + OCTETSTRING os; + codec.encode(p_utCamInitialize, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtCamChangePosition(const LibItsCam__TypesAndValues::UtCamChangePosition &p_utCamChangePosition) { + loggers::get_instance().log_msg(">>> fx__enc__UtCamChangePosition: ", p_utCamChangePosition); + + uppertester_cam_codec codec; + OCTETSTRING os; + codec.encode(p_utCamChangePosition, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtCamTrigger(const LibItsCam__TypesAndValues::UtCamTrigger &p_utCamTrigger) { + loggers::get_instance().log_msg(">>> fx__enc__UtCamTrigger: ", p_utCamTrigger); + + uppertester_cam_codec codec; + OCTETSTRING os; + codec.encode(p_utCamTrigger, os); + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a UtCamResults type + * @param value to encode + * @return encoded value + ****************************************************/ + INTEGER fx__dec__UtCamResults(BITSTRING &b, LibItsCam__TypesAndValues::UtCamResults &p) { + loggers::get_instance().log(">>> fx__dec__UtCamResults"); + + uppertester_cam_codec codec; + OCTETSTRING is = bit2oct(b); + std::unique_ptr ptr = codec.decode(is); + if (ptr == nullptr) { + loggers::get_instance().warning("fx__dec__UtCamResults: -1 result code was returned"); + return -1; + } + p = static_cast(*ptr); + return 0; + } + + /**************************************************** + * @desc External function to decode a UtCamEventInd type + * @param value to encode + * @return encoded value + ****************************************************/ + INTEGER fx__dec__UtCamEventInd(BITSTRING &b, LibItsCam__TypesAndValues::UtCamEventInd &p) { + loggers::get_instance().log(">>> fx__dec__UtCamEventInd"); + + uppertester_cam_codec codec; + OCTETSTRING is = bit2oct(b); + std::unique_ptr ptr = codec.decode(is); + if (ptr == nullptr) { + loggers::get_instance().warning("fx__dec__UtCamEventInd: -1 result code was returned"); + return -1; + } + p = static_cast(*ptr); + return 0; + } + +} // namespace LibItsCam__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsDenm_Encdec.cc b/ccsrc/EncDec/LibItsDenm_Encdec.cc index 4d86566b519e98e5f35608c826fdf96de2616c72..1997c5debf9baf54c6dbfbe0848cc322fbacc4b8 100644 --- a/ccsrc/EncDec/LibItsDenm_Encdec.cc +++ b/ccsrc/EncDec/LibItsDenm_Encdec.cc @@ -1,279 +1,279 @@ -#include - -#include "LibItsDenm_EncdecDeclarations.hh" - -#include "denm_codec.hh" -#include "loggers.hh" -#include "uppertester_denm_codec.hh" - -namespace LibItsDenm__EncdecDeclarations { - /**************************************************** - * @desc External function to encode a DenmReq type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__DenmReq(const LibItsDenm__TestSystem::DenmReq &p_denmReq) { - loggers::get_instance().log_msg(">>> fx__enc__DenmReq: ", p_denmReq); - - denm_codec codec; - OCTETSTRING os; - if (codec.encode(p_denmReq.msgOut(), os) == -1) { - loggers::get_instance().warning("fx__enc__DenmReq: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a DenmReq type - * @param value to encode - * @return encoded value - ****************************************************/ - INTEGER fx__dec__DenmReq(BITSTRING &b, LibItsDenm__TestSystem::DenmReq &p) { - loggers::get_instance().log(">>> fx__dec__DenmReq"); - - denm_codec codec; - DENM__PDU__Descriptions::DENM denm; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(is, denm) == -1) { - loggers::get_instance().warning("fx__dec__DenmReq: -1 result code was returned"); - return -1; - } - p.msgOut() = denm; - - return 0; - } - - INTEGER fx__dec__DenmInd(BITSTRING &b, LibItsDenm__TestSystem::DenmInd &p_denmInd) { - loggers::get_instance().log(">>> fx__dec__DenmInd"); - - denm_codec codec; - DENM__PDU__Descriptions::DENM denm; - OCTETSTRING is = bit2oct(b); - - int s = (LibItsDenm__TestSystem::DenmInd_gnNextHeader_raw_.fieldlength + LibItsDenm__TestSystem::DenmInd_gnHeaderType_raw_.fieldlength + - LibItsDenm__TestSystem::DenmInd_gnHeaderSubtype_raw_.fieldlength + LibItsDenm__TestSystem::DenmInd_gnLifetime_raw_.fieldlength + - LibItsDenm__TestSystem::DenmInd_gnTrafficClass_raw_.fieldlength + LibItsDenm__TestSystem::DenmInd_btpDestinationPort_raw_.fieldlength + - LibItsDenm__TestSystem::DenmInd_btpInfo_raw_.fieldlength + LibItsDenm__TestSystem::DenmInd_ssp_raw_.fieldlength + - LibItsDenm__TestSystem::DenmInd_its__aid_raw_.fieldlength) / - 8; - // Decode DEN message - if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), denm) == -1) { - loggers::get_instance().warning("fx__dec__DenmInd: -1 result code was returned"); - return -1; - } - p_denmInd.msgIn() = denm; - // Decode lower layer data - TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_gnNextHeader_raw_.fieldlength / 8)) { - p_denmInd.gnNextHeader().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.gnNextHeader() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: gnNextHeader=", p_denmInd.gnNextHeader()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_gnHeaderType_raw_.fieldlength / 8)) { - p_denmInd.gnHeaderType().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.gnHeaderType() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: gnHeaderType=", p_denmInd.gnHeaderType()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_gnHeaderSubtype_raw_.fieldlength / 8)) { - p_denmInd.gnHeaderSubtype().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.gnHeaderSubtype() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: gnHeaderSubType=", p_denmInd.gnHeaderSubtype()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_gnLifetime_raw_.fieldlength / 8)) { - p_denmInd.gnLifetime().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.gnLifetime() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: gnLifetime=", p_denmInd.gnLifetime()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_gnTrafficClass_raw_.fieldlength / 8)) { - p_denmInd.gnTrafficClass().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.gnTrafficClass() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: gnTrafficClass=", p_denmInd.gnTrafficClass()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_btpDestinationPort_raw_.fieldlength / 8)) { - p_denmInd.btpDestinationPort().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.btpDestinationPort() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: btpDestinationPort=", p_denmInd.btpDestinationPort()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_btpInfo_raw_.fieldlength / 8)) { - p_denmInd.btpInfo().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.btpInfo() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: btpInfo=", p_denmInd.btpInfo()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_ssp_raw_.fieldlength / 8)) { - p_denmInd.ssp().set_to_omit(); - } else { - BITSTRING bs; - bs.decode(LibItsDenm__TestSystem::DenmInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.ssp() = bs; - } - loggers::get_instance().log_msg("fx__dec__DENM: ssp=", p_denmInd.ssp()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TestSystem::DenmInd_its__aid_raw_.fieldlength / 8)) { - p_denmInd.its__aid().set_to_omit(); - } else { - OCTETSTRING os; - os.decode(LibItsDenm__TestSystem::DenmInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); - p_denmInd.its__aid() = oct2int(os); - } - loggers::get_instance().log_msg("fx__dec__DENM: its_aid=", p_denmInd.its__aid()); - loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); - - return 0; - } - - BITSTRING fx__enc__DENM(const DENM__PDU__Descriptions::DENM &p_denm) { - loggers::get_instance().log_msg(">>> fx__enc__DENM: ", p_denm); - - denm_codec codec; - OCTETSTRING os; - codec.encode(p_denm, os); - return oct2bit(os); - } - - INTEGER fx__dec__DENM(BITSTRING &b, DENM__PDU__Descriptions::DENM &p) { - loggers::get_instance().log(">>> fx__dec__DENM"); - denm_codec codec; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(OCTETSTRING(is.lengthof(), static_cast(is)), p) == -1) { - loggers::get_instance().warning("fx__dec__DENM: -1 result code was returned"); - return -1; - } - - return 0; - } - - BITSTRING fx__enc__UtDenmInitialize(const LibItsDenm__TypesAndValues::UtDenmInitialize &p_utDenmInitialize) { - loggers::get_instance().log_msg(">>> fx__enc__UtDenmInitialize: ", p_utDenmInitialize); - - uppertester_denm_codec codec; - OCTETSTRING os; - codec.encode(p_utDenmInitialize, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtDenmChangePosition(const LibItsDenm__TypesAndValues::UtDenmChangePosition &p_utDenmChangePosition) { - loggers::get_instance().log_msg(">>> fx__enc__UtDenmChangePosition: ", p_utDenmChangePosition); - - uppertester_denm_codec codec; - OCTETSTRING os; - codec.encode(p_utDenmChangePosition, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtDenmChangePseudonym(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &p_utDenmChangePseudonym) { - loggers::get_instance().log_msg(">>> fx__enc__UtDenmChangePseudonym: ", p_utDenmChangePseudonym); - - uppertester_denm_codec codec; - OCTETSTRING os; - codec.encode((const Record_Type &)p_utDenmChangePseudonym, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtDenmTrigger(const LibItsDenm__TypesAndValues::UtDenmTrigger &p_utDenmTrigger) { - loggers::get_instance().log_msg(">>> fx__enc__UtDenmTrigger: ", p_utDenmTrigger); - - uppertester_denm_codec codec; - OCTETSTRING os; - codec.encode(p_utDenmTrigger, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtDenmUpdate(const LibItsDenm__TypesAndValues::UtDenmUpdate &p_utDenmUpdate) { - loggers::get_instance().log_msg(">>> fx__enc__UtDenmUpdate: ", p_utDenmUpdate); - - uppertester_denm_codec codec; - OCTETSTRING os; - codec.encode(p_utDenmUpdate, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtDenmTermination(const LibItsDenm__TypesAndValues::UtDenmTermination &p_utDenmTermination) { - loggers::get_instance().log_msg(">>> fx__enc__UtDenmTermination: ", p_utDenmTermination); - - uppertester_denm_codec codec; - OCTETSTRING os; - codec.encode(p_utDenmTermination, os); - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a UtDenmResults type - * @param value to encode - * @return encoded value - ****************************************************/ - INTEGER fx__dec__UtDenmResults(BITSTRING &b, LibItsDenm__TypesAndValues::UtDenmResults &p) { - loggers::get_instance().log(">>> fx__dec__UtDenmResults"); - - uppertester_denm_codec codec; - OCTETSTRING is = bit2oct(b); - std::unique_ptr ptr = codec.decode(is); - if (ptr == nullptr) { - loggers::get_instance().warning("fx__dec__UtDenmResults: -1 result code was returned"); - return -1; - } - p = static_cast(*ptr); - return 0; - } - - /**************************************************** - * @desc External function to decode a UtDenmEventInd type - * @param value to encode - * @return encoded value - ****************************************************/ - INTEGER fx__dec__UtDenmEventInd(BITSTRING &b, LibItsDenm__TypesAndValues::UtDenmEventInd &p) { - loggers::get_instance().log(">>> fx__dec__UtDenmEventInd"); - - uppertester_denm_codec codec; - OCTETSTRING is = bit2oct(b); - std::unique_ptr ptr = codec.decode(is); - if (ptr == nullptr) { - loggers::get_instance().warning("fx__dec__UtDenmEventInd: -1 result code was returned"); - return -1; - } - p = static_cast(*ptr); - return 0; - } - -} // namespace LibItsDenm__EncdecDeclarations +#include + +#include "LibItsDenm_EncdecDeclarations.hh" + +#include "denm_codec.hh" +#include "loggers.hh" +#include "uppertester_denm_codec.hh" + +namespace LibItsDenm__EncdecDeclarations { + /**************************************************** + * @desc External function to encode a DenmReq type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__DenmReq(const LibItsDenm__TypesAndValues::DenmReq &p_denmReq) { + loggers::get_instance().log_msg(">>> fx__enc__DenmReq: ", p_denmReq); + + denm_codec codec; + OCTETSTRING os; + if (codec.encode(p_denmReq.msgOut(), os) == -1) { + loggers::get_instance().warning("fx__enc__DenmReq: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a DenmReq type + * @param value to encode + * @return encoded value + ****************************************************/ + INTEGER fx__dec__DenmReq(BITSTRING &b, LibItsDenm__TypesAndValues::DenmReq &p) { + loggers::get_instance().log(">>> fx__dec__DenmReq"); + + denm_codec codec; + DENM__PDU__Descriptions::DENM denm; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(is, denm) == -1) { + loggers::get_instance().warning("fx__dec__DenmReq: -1 result code was returned"); + return -1; + } + p.msgOut() = denm; + + return 0; + } + + INTEGER fx__dec__DenmInd(BITSTRING &b, LibItsDenm__TypesAndValues::DenmInd &p_denmInd) { + loggers::get_instance().log(">>> fx__dec__DenmInd"); + + denm_codec codec; + DENM__PDU__Descriptions::DENM denm; + OCTETSTRING is = bit2oct(b); + + int s = (LibItsDenm__TypesAndValues::DenmInd_gnNextHeader_raw_.fieldlength + LibItsDenm__TypesAndValues::DenmInd_gnHeaderType_raw_.fieldlength + + LibItsDenm__TypesAndValues::DenmInd_gnHeaderSubtype_raw_.fieldlength + LibItsDenm__TypesAndValues::DenmInd_gnLifetime_raw_.fieldlength + + LibItsDenm__TypesAndValues::DenmInd_gnTrafficClass_raw_.fieldlength + LibItsDenm__TypesAndValues::DenmInd_btpDestinationPort_raw_.fieldlength + + LibItsDenm__TypesAndValues::DenmInd_btpInfo_raw_.fieldlength + LibItsDenm__TypesAndValues::DenmInd_ssp_raw_.fieldlength + + LibItsDenm__TypesAndValues::DenmInd_its__aid_raw_.fieldlength) / + 8; + // Decode DEN message + if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), denm) == -1) { + loggers::get_instance().warning("fx__dec__DenmInd: -1 result code was returned"); + return -1; + } + p_denmInd.msgIn() = denm; + // Decode lower layer data + TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // gnNextHeader + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_gnNextHeader_raw_.fieldlength / 8)) { + p_denmInd.gnNextHeader().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.gnNextHeader() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: gnNextHeader=", p_denmInd.gnNextHeader()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // gnHeaderType + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_gnHeaderType_raw_.fieldlength / 8)) { + p_denmInd.gnHeaderType().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.gnHeaderType() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: gnHeaderType=", p_denmInd.gnHeaderType()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // gnHeaderSubtype + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + p_denmInd.gnHeaderSubtype().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.gnHeaderSubtype() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: gnHeaderSubType=", p_denmInd.gnHeaderSubtype()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // gnLifetime + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_gnLifetime_raw_.fieldlength / 8)) { + p_denmInd.gnLifetime().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.gnLifetime() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: gnLifetime=", p_denmInd.gnLifetime()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // gnTrafficClass + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_gnTrafficClass_raw_.fieldlength / 8)) { + p_denmInd.gnTrafficClass().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.gnTrafficClass() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: gnTrafficClass=", p_denmInd.gnTrafficClass()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // btpDestinationPort + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_btpDestinationPort_raw_.fieldlength / 8)) { + p_denmInd.btpDestinationPort().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.btpDestinationPort() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: btpDestinationPort=", p_denmInd.btpDestinationPort()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // btpInfo + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_btpInfo_raw_.fieldlength / 8)) { + p_denmInd.btpInfo().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.btpInfo() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: btpInfo=", p_denmInd.btpInfo()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // ssp + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_ssp_raw_.fieldlength / 8)) { + p_denmInd.ssp().set_to_omit(); + } else { + BITSTRING bs; + bs.decode(LibItsDenm__TypesAndValues::DenmInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.ssp() = bs; + } + loggers::get_instance().log_msg("fx__dec__DENM: ssp=", p_denmInd.ssp()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + // its__aid + if (decoding_buffer.get_read_len() < static_cast(LibItsDenm__TypesAndValues::DenmInd_its__aid_raw_.fieldlength / 8)) { + p_denmInd.its__aid().set_to_omit(); + } else { + OCTETSTRING os; + os.decode(LibItsDenm__TypesAndValues::DenmInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + p_denmInd.its__aid() = oct2int(os); + } + loggers::get_instance().log_msg("fx__dec__DENM: its_aid=", p_denmInd.its__aid()); + loggers::get_instance().log_to_hexa("fx__dec__DENM: ", decoding_buffer); + + return 0; + } + + BITSTRING fx__enc__DENM(const DENM__PDU__Descriptions::DENM &p_denm) { + loggers::get_instance().log_msg(">>> fx__enc__DENM: ", p_denm); + + denm_codec codec; + OCTETSTRING os; + codec.encode(p_denm, os); + return oct2bit(os); + } + + INTEGER fx__dec__DENM(BITSTRING &b, DENM__PDU__Descriptions::DENM &p) { + loggers::get_instance().log(">>> fx__dec__DENM"); + denm_codec codec; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(OCTETSTRING(is.lengthof(), static_cast(is)), p) == -1) { + loggers::get_instance().warning("fx__dec__DENM: -1 result code was returned"); + return -1; + } + + return 0; + } + + BITSTRING fx__enc__UtDenmInitialize(const LibItsDenm__TypesAndValues::UtDenmInitialize &p_utDenmInitialize) { + loggers::get_instance().log_msg(">>> fx__enc__UtDenmInitialize: ", p_utDenmInitialize); + + uppertester_denm_codec codec; + OCTETSTRING os; + codec.encode(p_utDenmInitialize, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtDenmChangePosition(const LibItsDenm__TypesAndValues::UtDenmChangePosition &p_utDenmChangePosition) { + loggers::get_instance().log_msg(">>> fx__enc__UtDenmChangePosition: ", p_utDenmChangePosition); + + uppertester_denm_codec codec; + OCTETSTRING os; + codec.encode(p_utDenmChangePosition, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtDenmChangePseudonym(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &p_utDenmChangePseudonym) { + loggers::get_instance().log_msg(">>> fx__enc__UtDenmChangePseudonym: ", p_utDenmChangePseudonym); + + uppertester_denm_codec codec; + OCTETSTRING os; + codec.encode((const Record_Type &)p_utDenmChangePseudonym, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtDenmTrigger(const LibItsDenm__TypesAndValues::UtDenmTrigger &p_utDenmTrigger) { + loggers::get_instance().log_msg(">>> fx__enc__UtDenmTrigger: ", p_utDenmTrigger); + + uppertester_denm_codec codec; + OCTETSTRING os; + codec.encode(p_utDenmTrigger, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtDenmUpdate(const LibItsDenm__TypesAndValues::UtDenmUpdate &p_utDenmUpdate) { + loggers::get_instance().log_msg(">>> fx__enc__UtDenmUpdate: ", p_utDenmUpdate); + + uppertester_denm_codec codec; + OCTETSTRING os; + codec.encode(p_utDenmUpdate, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtDenmTermination(const LibItsDenm__TypesAndValues::UtDenmTermination &p_utDenmTermination) { + loggers::get_instance().log_msg(">>> fx__enc__UtDenmTermination: ", p_utDenmTermination); + + uppertester_denm_codec codec; + OCTETSTRING os; + codec.encode(p_utDenmTermination, os); + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a UtDenmResults type + * @param value to encode + * @return encoded value + ****************************************************/ + INTEGER fx__dec__UtDenmResults(BITSTRING &b, LibItsDenm__TypesAndValues::UtDenmResults &p) { + loggers::get_instance().log(">>> fx__dec__UtDenmResults"); + + uppertester_denm_codec codec; + OCTETSTRING is = bit2oct(b); + std::unique_ptr ptr = codec.decode(is); + if (ptr == nullptr) { + loggers::get_instance().warning("fx__dec__UtDenmResults: -1 result code was returned"); + return -1; + } + p = static_cast(*ptr); + return 0; + } + + /**************************************************** + * @desc External function to decode a UtDenmEventInd type + * @param value to encode + * @return encoded value + ****************************************************/ + INTEGER fx__dec__UtDenmEventInd(BITSTRING &b, LibItsDenm__TypesAndValues::UtDenmEventInd &p) { + loggers::get_instance().log(">>> fx__dec__UtDenmEventInd"); + + uppertester_denm_codec codec; + OCTETSTRING is = bit2oct(b); + std::unique_ptr ptr = codec.decode(is); + if (ptr == nullptr) { + loggers::get_instance().warning("fx__dec__UtDenmEventInd: -1 result code was returned"); + return -1; + } + p = static_cast(*ptr); + return 0; + } + +} // namespace LibItsDenm__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsEvcsn_Encdec.cc b/ccsrc/EncDec/LibItsEvcsn_Encdec.cc index cc4b0456072ccadc8beaf32f8140f77179b58da5..36930b80cef75e59bfcfea1127d40a2ac5415032 100644 --- a/ccsrc/EncDec/LibItsEvcsn_Encdec.cc +++ b/ccsrc/EncDec/LibItsEvcsn_Encdec.cc @@ -1,37 +1,37 @@ -#include "LibItsEvcsn_EncdecDeclarations.hh" - -namespace LibItsEvcsn__EncdecDeclarations { - /**************************************************** - * @desc External function to encode a EvcsnReq type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__EvcsnReq(const LibItsEvcsn__TestSystem::EvcsnReq &p) { - // set error behavior - TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); - - TTCN_Buffer TTCN_buf; - TTCN_buf.clear(); - - // encode message in BER (CER variant, but can be any) - p.msgOut().encode(EVCSN__PDU__Descriptions::EvcsnPdu_descr_, TTCN_buf, TTCN_EncDec::CT_BER, BER_ENCODE_CER); - - OCTETSTRING encodedData(TTCN_buf.get_len(), TTCN_buf.get_data()); - - // insert BER2PER recoding here! - - return oct2bit(encodedData); - } - - /**************************************************** - * @desc External function to decode a DenmReq type - * @param value to encode - * @return encoded value - ****************************************************/ - /* TODO RGy function not implemented! (decvalue() not used by test suite @29-06-2016) - INTEGER fx__dec__EvcsnReq(BITSTRING& b, LibItsEvcsn__TestSystem::EvcsnReq& p) - { - return -1; - } - */ -} // namespace LibItsEvcsn__EncdecDeclarations +#include "LibItsEvcsn_EncdecDeclarations.hh" + +namespace LibItsEvcsn__EncdecDeclarations { + /**************************************************** + * @desc External function to encode a EvcsnReq type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__EvcsnReq(const LibItsEvcsn__TestSystem::EvcsnReq &p) { + // set error behavior + TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); + + TTCN_Buffer TTCN_buf; + TTCN_buf.clear(); + + // encode message in BER (CER variant, but can be any) + p.msgOut().encode(EVCSN__PDU__Descriptions::EvcsnPdu_descr_, TTCN_buf, TTCN_EncDec::CT_BER, BER_ENCODE_CER); + + OCTETSTRING encodedData(TTCN_buf.get_len(), TTCN_buf.get_data()); + + // insert BER2PER recoding here! + + return oct2bit(encodedData); + } + + /**************************************************** + * @desc External function to decode a DenmReq type + * @param value to encode + * @return encoded value + ****************************************************/ + /* TODO RGy function not implemented! (decvalue() not used by test suite @29-06-2016) + INTEGER fx__dec__EvcsnReq(BITSTRING& b, LibItsEvcsn__TestSystem::EvcsnReq& p) + { + return -1; + } + */ +} // namespace LibItsEvcsn__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsGeoNetworking_Encdec.cc b/ccsrc/EncDec/LibItsGeoNetworking_Encdec.cc index 01aca20b2617bacfcbeab6b7abef06a40327f869..a15ee8a75c3c4e1ef4d7abf705732606fa2f57d5 100644 --- a/ccsrc/EncDec/LibItsGeoNetworking_Encdec.cc +++ b/ccsrc/EncDec/LibItsGeoNetworking_Encdec.cc @@ -1,268 +1,268 @@ -/*! - * \file LibItsGeoNetworking_EncdecDeclarations.cc - * \brief Implementation file for GeoNetworking 'encvalue'/'decvalue'. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include "LibItsGeoNetworking_EncdecDeclarations.hh" - -#include "geonetworking_codec.hh" -#include "loggers.hh" -#include "uppertester_geonetworking_codec.hh" - -namespace LibItsGeoNetworking__EncdecDeclarations { - - /**************************************************** - * \brief External function to encode a GeoNetworkingReq type - * \param[in] p_geoNetworkingReq The value to encode - * \return encoded value - ****************************************************/ - BITSTRING fx__enc__GeoNetworkingReq(LibItsGeoNetworking__TestSystem::GeoNetworkingReq const &p_geoNetworkingReq) { - loggers::get_instance().log_msg(">>> fx__enc__GeoNetworkingReq: ", p_geoNetworkingReq); - - float duration; - std::string tag("fx__enc__GeoNetworkingReq"); - loggers::get_instance().set_start_time(tag); - geonetworking_codec codec; - OCTETSTRING os; - if (codec.encode(p_geoNetworkingReq.msgOut(), os) == -1) { - loggers::get_instance().warning("fx__enc__GeoNetworkingReq: -1 result code was returned"); - return int2bit(0, 1); - } - TTCN_Buffer encoding_buffer(os); - for (int i = 1; i < p_geoNetworkingReq.get_count(); i++) { - loggers::get_instance().log("fx__enc__GeoNetworkingReq: processing %s/%s/%s - %d - %d", p_geoNetworkingReq.fld_name(i), - p_geoNetworkingReq.fld_descr(i)->name, p_geoNetworkingReq.get_at(i)->get_descriptor()->name, - p_geoNetworkingReq.get_at(i)->is_optional(), p_geoNetworkingReq.get_at(i)->is_present()); - if (p_geoNetworkingReq.get_at(i)->is_optional() && p_geoNetworkingReq.get_at(i)->is_present()) { - p_geoNetworkingReq.get_at(i)->get_opt_value()->encode(*p_geoNetworkingReq.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); - } else { - p_geoNetworkingReq.get_at(i)->encode(*p_geoNetworkingReq.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); - } - } // End of 'for' statement - loggers::get_instance().set_stop_time(tag, duration); - - return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); - } // End of function fx__enc__GeoNetworkingReq - - /**************************************************** - * @desc External function to decode a GeoNetworkingReq type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__GeoNetworkingReq(BITSTRING &b, LibItsGeoNetworking__TestSystem::GeoNetworkingReq &p) { - loggers::get_instance().log(">>> fx__dec__GeoNetworkingReq"); - geonetworking_codec codec; - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu pdu; - OCTETSTRING is = bit2oct(b); - - // Calculate the size of the lower layers information - unsigned int s = (LibItsGeoNetworking__TestSystem::GeoNetworkingInd_macDestinationAddress_raw_.fieldlength + - LibItsGeoNetworking__TestSystem::GeoNetworkingInd_its__aid_raw_.fieldlength) / - 8; - if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), pdu) == -1) { - loggers::get_instance().warning("fx__dec__GeoNetworkingReq: -1 result code was returned"); - return -1; - } - p.msgOut() = pdu; - TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); - loggers::get_instance().log_to_hexa("fx__dec__GeoNetworkingInd: Lower layer: ", decoding_buffer); - for (int i = 1; i < p.get_count(); i++) { - loggers::get_instance().log("fx__dec__GeoNetworkingReq: processing %s/%s/%s", p.fld_name(i), p.fld_descr(i)->name, p.get_at(i)->get_descriptor()->name); - p.get_at(i)->decode(*p.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); - } // End of 'for' statement - - return 0; - } - - /**************************************************** - * @desc External function to encode a GeoNetworkingInd type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__GeoNetworkingInd(LibItsGeoNetworking__TestSystem::GeoNetworkingInd const &p_geoNetworkingInd) { - loggers::get_instance().log_msg(">>> fx__enc__GeoNetworkingInd: ", p_geoNetworkingInd); - - geonetworking_codec codec; - OCTETSTRING os; - if (codec.encode(p_geoNetworkingInd.msgIn(), os) == -1) { - loggers::get_instance().warning("fx__enc__GeoNetworkingInd: -1 result code was returned"); - return int2bit(0, 1); - } - TTCN_Buffer encoding_buffer(os); - for (int i = 1; i < p_geoNetworkingInd.get_count(); i++) { - loggers::get_instance().log("fx__enc__GeoNetworkingInd: processing %s/%s/%s - %d - %d", p_geoNetworkingInd.fld_name(i), - p_geoNetworkingInd.fld_descr(i)->name, p_geoNetworkingInd.get_at(i)->get_descriptor()->name, - p_geoNetworkingInd.get_at(i)->is_optional(), p_geoNetworkingInd.get_at(i)->is_present()); - if (p_geoNetworkingInd.get_at(i)->is_optional() && p_geoNetworkingInd.get_at(i)->is_present()) { - p_geoNetworkingInd.get_at(i)->get_opt_value()->encode(*p_geoNetworkingInd.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); - } else { - p_geoNetworkingInd.get_at(i)->encode(*p_geoNetworkingInd.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); - } - } // End of 'for' statement - - return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); - } - - /**************************************************** - * @desc External function to decode a GeoNetworkingInd type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__GeoNetworkingInd(BITSTRING &b, LibItsGeoNetworking__TestSystem::GeoNetworkingInd &p_geoNetworkingInd) { - loggers::get_instance().log(">>> fx__dec__GeoNetworkingInd"); - - float duration; - std::string tag("fx__dec__GeoNetworkingInd"); - loggers::get_instance().set_start_time(tag); - - geonetworking_codec codec; - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu pdu; - OCTETSTRING is = bit2oct(b); - - // Calculate the size of the lower layers information - unsigned int s = - (LibItsGeoNetworking__TestSystem::GeoNetworkingInd_macDestinationAddress_raw_.fieldlength + - LibItsGeoNetworking__TestSystem::GeoNetworkingInd_ssp_raw_.fieldlength + LibItsGeoNetworking__TestSystem::GeoNetworkingInd_its__aid_raw_.fieldlength) / - 8; - if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), pdu) == -1) { - loggers::get_instance().warning("fx__dec__GeoNetworkingInd: -1 result code was returned"); - return -1; - } - p_geoNetworkingInd.msgIn() = pdu; - TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); - loggers::get_instance().log_to_hexa("fx__dec__GeoNetworkingInd: Lower layer: ", decoding_buffer); - for (int i = 1; i < p_geoNetworkingInd.get_count(); i++) { - loggers::get_instance().log("fx__dec__GeoNetworkingInd: processing %s/%s/%s - %d - %d", p_geoNetworkingInd.fld_name(i), - p_geoNetworkingInd.fld_descr(i)->name, p_geoNetworkingInd.get_at(i)->get_descriptor()->name, - p_geoNetworkingInd.get_at(i)->is_optional(), p_geoNetworkingInd.get_at(i)->is_present()); - if (p_geoNetworkingInd.get_at(i)->is_optional()) { - loggers::get_instance().log("fx__dec__GeoNetworkingInd: Bytes remaining: %d - field lenth: %d", decoding_buffer.get_len() - decoding_buffer.get_pos(), - p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8); - if (std::string(p_geoNetworkingInd.fld_name(i)).compare("ssp") == 0) { - if ((decoding_buffer.get_len() - decoding_buffer.get_pos()) >= (unsigned int)p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8) { - loggers::get_instance().log("fx__dec__GeoNetworkingInd: decoding %s", p_geoNetworkingInd.fld_descr(i)->name); - BITSTRING ssp; - ssp.decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); - loggers::get_instance().log_msg("fx__dec__GeoNetworkingInd: ssp=", ssp); - dynamic_cast &>(*p_geoNetworkingInd.get_at(i)) = OPTIONAL(ssp); - } else { - loggers::get_instance().log("fx__dec__GeoNetworkingInd: set %s to omit", p_geoNetworkingInd.fld_descr(i)->name); - dynamic_cast &>(*p_geoNetworkingInd.get_at(i)).set_to_omit(); - } - } else if (std::string(p_geoNetworkingInd.fld_name(i)).compare("its_aid") == 0) { - loggers::get_instance().log("fx__dec__GeoNetworkingInd: Bytes remaining: %d - its_aid lenth: %d", - decoding_buffer.get_len() - decoding_buffer.get_pos(), p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8); - if ((decoding_buffer.get_len() - decoding_buffer.get_pos()) >= (unsigned int)p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8) { - INTEGER its_aid; - its_aid.decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); - loggers::get_instance().log_msg("fx__dec__GeoNetworkingInd: its_aid=", its_aid); - dynamic_cast &>(*p_geoNetworkingInd.get_at(i)) = OPTIONAL(its_aid); - } else { - loggers::get_instance().log("fx__dec__GeoNetworkingInd: set %s to omit", p_geoNetworkingInd.fld_descr(i)->name); - dynamic_cast &>(*p_geoNetworkingInd.get_at(i)).set_to_omit(); - } - } else { - loggers::get_instance().log("fx__dec__GeoNetworkingInd(1): decoding %s", p_geoNetworkingInd.fld_descr(i)->name); - p_geoNetworkingInd.get_at(i)->decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); - } - } else { - loggers::get_instance().log("fx__dec__GeoNetworkingInd(2): decoding %s", p_geoNetworkingInd.fld_descr(i)->name); - p_geoNetworkingInd.get_at(i)->decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); - } - } // End of 'for' statement - loggers::get_instance().set_stop_time(tag, duration); - - loggers::get_instance().log_msg("<<< fx__dec__GeoNetworkingInd: ", p_geoNetworkingInd); - return 0; - } - - /**************************************************** - * @desc External function to encode a GeoNetworkingPdu type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__GeoNetworkingPdu(LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu const &p_geoNetworkingPdu) { - loggers::get_instance().log_msg(">>> fx__enc__GeoNetworkingPdu: ", p_geoNetworkingPdu); - - geonetworking_codec codec; - OCTETSTRING os; - codec.encode(p_geoNetworkingPdu, os); - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a GeoNetworkingPdu type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__GeoNetworkingPdu(BITSTRING &b, LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &p) { - loggers::get_instance().log(">>> fx__dec__GeoNetworkingPdu"); - geonetworking_codec codec; - OCTETSTRING is = bit2oct(b); - - if (codec.decode(OCTETSTRING(is.lengthof(), static_cast(is)), p) == -1) { - loggers::get_instance().warning("fx__dec__GeoNetworkingPdu: -1 result code was returned"); - return -1; - } - - return 0; - } - - /**************************************************** - * @desc External function to encode a GnNonSecuredPacket type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__GnNonSecuredPacket(const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p_gnNonSecuredPacket) { - loggers::get_instance().log_msg(">>> fx__enc__GnNonSecuredPacket: ", p_gnNonSecuredPacket); - - geonetworking_codec codec; - OCTETSTRING os; - codec.encode(p_gnNonSecuredPacket, os); - return oct2bit(os); - } - - /**************************************************** - * @desc External function to decode a GnNonSecuredPacket type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__GnNonSecuredPacket(BITSTRING &b, LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p) { return -1; } - - BITSTRING fx__enc__UtGnInitialize(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &p_utGnInitialize) { - loggers::get_instance().log_msg(">>> fx__enc__UtGnInitialize: ", p_utGnInitialize); - - uppertester_geonetworking_codec codec; - OCTETSTRING os; - codec.encode(p_utGnInitialize, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtGnChangePosition(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &p_utGnChangePosition) { - loggers::get_instance().log_msg(">>> fx__enc__UtGnChangePosition: ", p_utGnChangePosition); - - uppertester_geonetworking_codec codec; - OCTETSTRING os; - codec.encode(p_utGnChangePosition, os); - return oct2bit(os); - } - - BITSTRING fx__enc__UtGnTrigger(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &p_utGnTrigger) { - loggers::get_instance().log_msg(">>> fx__enc__UtGnTrigger: ", p_utGnTrigger); - - uppertester_geonetworking_codec codec; - OCTETSTRING os; - codec.encode(p_utGnTrigger, os); - return oct2bit(os); - } - -} // namespace LibItsGeoNetworking__EncdecDeclarations +/*! + * \file LibItsGeoNetworking_EncdecDeclarations.cc + * \brief Implementation file for GeoNetworking 'encvalue'/'decvalue'. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include "LibItsGeoNetworking_EncdecDeclarations.hh" + +#include "geonetworking_codec.hh" +#include "loggers.hh" +#include "uppertester_geonetworking_codec.hh" + +namespace LibItsGeoNetworking__EncdecDeclarations { + + /**************************************************** + * \brief External function to encode a GeoNetworkingReq type + * \param[in] p_geoNetworkingReq The value to encode + * \return encoded value + ****************************************************/ + BITSTRING fx__enc__GeoNetworkingReq(LibItsGeoNetworking__TypesAndValues::GeoNetworkingReq const &p_geoNetworkingReq) { + loggers::get_instance().log_msg(">>> fx__enc__GeoNetworkingReq: ", p_geoNetworkingReq); + + float duration; + std::string tag("fx__enc__GeoNetworkingReq"); + loggers::get_instance().set_start_time(tag); + geonetworking_codec codec; + OCTETSTRING os; + if (codec.encode(p_geoNetworkingReq.msgOut(), os) == -1) { + loggers::get_instance().warning("fx__enc__GeoNetworkingReq: -1 result code was returned"); + return int2bit(0, 1); + } + TTCN_Buffer encoding_buffer(os); + for (int i = 1; i < p_geoNetworkingReq.get_count(); i++) { + loggers::get_instance().log("fx__enc__GeoNetworkingReq: processing %s/%s/%s - %d - %d", p_geoNetworkingReq.fld_name(i), + p_geoNetworkingReq.fld_descr(i)->name, p_geoNetworkingReq.get_at(i)->get_descriptor()->name, + p_geoNetworkingReq.get_at(i)->is_optional(), p_geoNetworkingReq.get_at(i)->is_present()); + if (p_geoNetworkingReq.get_at(i)->is_optional() && p_geoNetworkingReq.get_at(i)->is_present()) { + p_geoNetworkingReq.get_at(i)->get_opt_value()->encode(*p_geoNetworkingReq.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); + } else { + p_geoNetworkingReq.get_at(i)->encode(*p_geoNetworkingReq.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); + } + } // End of 'for' statement + loggers::get_instance().set_stop_time(tag, duration); + + return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); + } // End of function fx__enc__GeoNetworkingReq + + /**************************************************** + * @desc External function to decode a GeoNetworkingReq type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__GeoNetworkingReq(BITSTRING &b, LibItsGeoNetworking__TypesAndValues::GeoNetworkingReq &p) { + loggers::get_instance().log(">>> fx__dec__GeoNetworkingReq"); + geonetworking_codec codec; + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu pdu; + OCTETSTRING is = bit2oct(b); + + // Calculate the size of the lower layers information + unsigned int s = (LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd_macDestinationAddress_raw_.fieldlength + + LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd_its__aid_raw_.fieldlength) / + 8; + if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), pdu) == -1) { + loggers::get_instance().warning("fx__dec__GeoNetworkingReq: -1 result code was returned"); + return -1; + } + p.msgOut() = pdu; + TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); + loggers::get_instance().log_to_hexa("fx__dec__GeoNetworkingInd: Lower layer: ", decoding_buffer); + for (int i = 1; i < p.get_count(); i++) { + loggers::get_instance().log("fx__dec__GeoNetworkingReq: processing %s/%s/%s", p.fld_name(i), p.fld_descr(i)->name, p.get_at(i)->get_descriptor()->name); + p.get_at(i)->decode(*p.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); + } // End of 'for' statement + + return 0; + } + + /**************************************************** + * @desc External function to encode a GeoNetworkingInd type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__GeoNetworkingInd(LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd const &p_geoNetworkingInd) { + loggers::get_instance().log_msg(">>> fx__enc__GeoNetworkingInd: ", p_geoNetworkingInd); + + geonetworking_codec codec; + OCTETSTRING os; + if (codec.encode(p_geoNetworkingInd.msgIn(), os) == -1) { + loggers::get_instance().warning("fx__enc__GeoNetworkingInd: -1 result code was returned"); + return int2bit(0, 1); + } + TTCN_Buffer encoding_buffer(os); + for (int i = 1; i < p_geoNetworkingInd.get_count(); i++) { + loggers::get_instance().log("fx__enc__GeoNetworkingInd: processing %s/%s/%s - %d - %d", p_geoNetworkingInd.fld_name(i), + p_geoNetworkingInd.fld_descr(i)->name, p_geoNetworkingInd.get_at(i)->get_descriptor()->name, + p_geoNetworkingInd.get_at(i)->is_optional(), p_geoNetworkingInd.get_at(i)->is_present()); + if (p_geoNetworkingInd.get_at(i)->is_optional() && p_geoNetworkingInd.get_at(i)->is_present()) { + p_geoNetworkingInd.get_at(i)->get_opt_value()->encode(*p_geoNetworkingInd.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); + } else { + p_geoNetworkingInd.get_at(i)->encode(*p_geoNetworkingInd.fld_descr(i), encoding_buffer, TTCN_EncDec::CT_RAW); + } + } // End of 'for' statement + + return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); + } + + /**************************************************** + * @desc External function to decode a GeoNetworkingInd type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__GeoNetworkingInd(BITSTRING &b, LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd &p_geoNetworkingInd) { + loggers::get_instance().log(">>> fx__dec__GeoNetworkingInd"); + + float duration; + std::string tag("fx__dec__GeoNetworkingInd"); + loggers::get_instance().set_start_time(tag); + + geonetworking_codec codec; + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu pdu; + OCTETSTRING is = bit2oct(b); + + // Calculate the size of the lower layers information + unsigned int s = + (LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd_macDestinationAddress_raw_.fieldlength + + LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd_ssp_raw_.fieldlength + LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd_its__aid_raw_.fieldlength) / + 8; + if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), pdu) == -1) { + loggers::get_instance().warning("fx__dec__GeoNetworkingInd: -1 result code was returned"); + return -1; + } + p_geoNetworkingInd.msgIn() = pdu; + TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); + loggers::get_instance().log_to_hexa("fx__dec__GeoNetworkingInd: Lower layer: ", decoding_buffer); + for (int i = 1; i < p_geoNetworkingInd.get_count(); i++) { + loggers::get_instance().log("fx__dec__GeoNetworkingInd: processing %s/%s/%s - %d - %d", p_geoNetworkingInd.fld_name(i), + p_geoNetworkingInd.fld_descr(i)->name, p_geoNetworkingInd.get_at(i)->get_descriptor()->name, + p_geoNetworkingInd.get_at(i)->is_optional(), p_geoNetworkingInd.get_at(i)->is_present()); + if (p_geoNetworkingInd.get_at(i)->is_optional()) { + loggers::get_instance().log("fx__dec__GeoNetworkingInd: Bytes remaining: %d - field lenth: %d", decoding_buffer.get_len() - decoding_buffer.get_pos(), + p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8); + if (std::string(p_geoNetworkingInd.fld_name(i)).compare("ssp") == 0) { + if ((decoding_buffer.get_len() - decoding_buffer.get_pos()) >= (unsigned int)p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8) { + loggers::get_instance().log("fx__dec__GeoNetworkingInd: decoding %s", p_geoNetworkingInd.fld_descr(i)->name); + BITSTRING ssp; + ssp.decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); + loggers::get_instance().log_msg("fx__dec__GeoNetworkingInd: ssp=", ssp); + dynamic_cast &>(*p_geoNetworkingInd.get_at(i)) = OPTIONAL(ssp); + } else { + loggers::get_instance().log("fx__dec__GeoNetworkingInd: set %s to omit", p_geoNetworkingInd.fld_descr(i)->name); + dynamic_cast &>(*p_geoNetworkingInd.get_at(i)).set_to_omit(); + } + } else if (std::string(p_geoNetworkingInd.fld_name(i)).compare("its_aid") == 0) { + loggers::get_instance().log("fx__dec__GeoNetworkingInd: Bytes remaining: %d - its_aid lenth: %d", + decoding_buffer.get_len() - decoding_buffer.get_pos(), p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8); + if ((decoding_buffer.get_len() - decoding_buffer.get_pos()) >= (unsigned int)p_geoNetworkingInd.fld_descr(i)->raw->fieldlength / 8) { + INTEGER its_aid; + its_aid.decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); + loggers::get_instance().log_msg("fx__dec__GeoNetworkingInd: its_aid=", its_aid); + dynamic_cast &>(*p_geoNetworkingInd.get_at(i)) = OPTIONAL(its_aid); + } else { + loggers::get_instance().log("fx__dec__GeoNetworkingInd: set %s to omit", p_geoNetworkingInd.fld_descr(i)->name); + dynamic_cast &>(*p_geoNetworkingInd.get_at(i)).set_to_omit(); + } + } else { + loggers::get_instance().log("fx__dec__GeoNetworkingInd(1): decoding %s", p_geoNetworkingInd.fld_descr(i)->name); + p_geoNetworkingInd.get_at(i)->decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); + } + } else { + loggers::get_instance().log("fx__dec__GeoNetworkingInd(2): decoding %s", p_geoNetworkingInd.fld_descr(i)->name); + p_geoNetworkingInd.get_at(i)->decode(*p_geoNetworkingInd.fld_descr(i), decoding_buffer, TTCN_EncDec::CT_RAW); + } + } // End of 'for' statement + loggers::get_instance().set_stop_time(tag, duration); + + loggers::get_instance().log_msg("<<< fx__dec__GeoNetworkingInd: ", p_geoNetworkingInd); + return 0; + } + + /**************************************************** + * @desc External function to encode a GeoNetworkingPdu type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__GeoNetworkingPdu(LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu const &p_geoNetworkingPdu) { + loggers::get_instance().log_msg(">>> fx__enc__GeoNetworkingPdu: ", p_geoNetworkingPdu); + + geonetworking_codec codec; + OCTETSTRING os; + codec.encode(p_geoNetworkingPdu, os); + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a GeoNetworkingPdu type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__GeoNetworkingPdu(BITSTRING &b, LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &p) { + loggers::get_instance().log(">>> fx__dec__GeoNetworkingPdu"); + geonetworking_codec codec; + OCTETSTRING is = bit2oct(b); + + if (codec.decode(OCTETSTRING(is.lengthof(), static_cast(is)), p) == -1) { + loggers::get_instance().warning("fx__dec__GeoNetworkingPdu: -1 result code was returned"); + return -1; + } + + return 0; + } + + /**************************************************** + * @desc External function to encode a GnNonSecuredPacket type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__GnNonSecuredPacket(const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p_gnNonSecuredPacket) { + loggers::get_instance().log_msg(">>> fx__enc__GnNonSecuredPacket: ", p_gnNonSecuredPacket); + + geonetworking_codec codec; + OCTETSTRING os; + codec.encode(p_gnNonSecuredPacket, os); + return oct2bit(os); + } + + /**************************************************** + * @desc External function to decode a GnNonSecuredPacket type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__GnNonSecuredPacket(BITSTRING &b, LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p) { return -1; } + + BITSTRING fx__enc__UtGnInitialize(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &p_utGnInitialize) { + loggers::get_instance().log_msg(">>> fx__enc__UtGnInitialize: ", p_utGnInitialize); + + uppertester_geonetworking_codec codec; + OCTETSTRING os; + codec.encode(p_utGnInitialize, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtGnChangePosition(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &p_utGnChangePosition) { + loggers::get_instance().log_msg(">>> fx__enc__UtGnChangePosition: ", p_utGnChangePosition); + + uppertester_geonetworking_codec codec; + OCTETSTRING os; + codec.encode(p_utGnChangePosition, os); + return oct2bit(os); + } + + BITSTRING fx__enc__UtGnTrigger(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &p_utGnTrigger) { + loggers::get_instance().log_msg(">>> fx__enc__UtGnTrigger: ", p_utGnTrigger); + + uppertester_geonetworking_codec codec; + OCTETSTRING os; + codec.encode(p_utGnTrigger, os); + return oct2bit(os); + } + +} // namespace LibItsGeoNetworking__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsHttp_Encdec.cc b/ccsrc/EncDec/LibItsHttp_Encdec.cc index 4eb83791b9dd3025633490a48c8bfd5989e369e6..89fe0d10a23ecbe07a8080ec3c04a773d6fcf4fa 100644 --- a/ccsrc/EncDec/LibItsHttp_Encdec.cc +++ b/ccsrc/EncDec/LibItsHttp_Encdec.cc @@ -1,28 +1,28 @@ - -#include "LibItsHttp_MessageBodyTypes.hh" - -#include "http_codec.hh" - -#include "loggers.hh" - -namespace LibItsHttp__EncdecDeclarations { - - BITSTRING fx__enc__http__message(const LibItsHttp__TypesAndValues::HttpMessage& p) { - loggers::get_instance().log_msg(">>> fx__enc__http__message: ", (const Base_Type&)p); - - OCTETSTRING os; - http_codec codec; - codec.encode(p, os); - - return oct2bit(os); - } - INTEGER fx__dec__http__message(BITSTRING& pdu, LibItsHttp__TypesAndValues::HttpMessage& p) { - loggers::get_instance().log_msg(">>> fx__dec__http__message: ", pdu); - - OCTETSTRING os = bit2oct(pdu); - http_codec codec; - codec.decode(os, p); - - return 0; - } -} // End of namespace LibItsHttp__EncdecDeclarations + +#include "LibItsHttp_MessageBodyTypes.hh" + +#include "http_codec.hh" + +#include "loggers.hh" + +namespace LibItsHttp__EncdecDeclarations { + + BITSTRING fx__enc__http__message(const LibItsHttp__TypesAndValues::HttpMessage& p) { + loggers::get_instance().log_msg(">>> fx__enc__http__message: ", (const Base_Type&)p); + + OCTETSTRING os; + http_codec codec; + codec.encode(p, os); + + return oct2bit(os); + } + INTEGER fx__dec__http__message(BITSTRING& pdu, LibItsHttp__TypesAndValues::HttpMessage& p) { + loggers::get_instance().log_msg(">>> fx__dec__http__message: ", pdu); + + OCTETSTRING os = bit2oct(pdu); + http_codec codec; + codec.decode(os, p); + + return 0; + } +} // End of namespace LibItsHttp__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsIpv6OverGeoNetworking_Encdec.cc b/ccsrc/EncDec/LibItsIpv6OverGeoNetworking_Encdec.cc index 4b172ba901827075aa5489d747c6ee9bc1e3c4ce..63728d17f7ce44b5c39071c74a05fa06cb8a45aa 100644 --- a/ccsrc/EncDec/LibItsIpv6OverGeoNetworking_Encdec.cc +++ b/ccsrc/EncDec/LibItsIpv6OverGeoNetworking_Encdec.cc @@ -1,20 +1,20 @@ -#include "LibItsIpv6OverGeoNetworking_EncdecDeclarations.hh" - -namespace LibItsIpv6OverGeoNetworking__EncdecDeclarations { - - /**************************************************** - * @desc External function to encode a Ipv6Packet type - * @param value to encode - * @return encoded value - ****************************************************/ - BITSTRING fx__enc__Ipv6Packet(const LibItsIpv6OverGeoNetworking__TypesAndValues::Ipv6Packet &p) { return int2bit(0, 8); } - - /**************************************************** - * @desc External function to decode a Ipv6Packet type - * @param value to encode - * @return encoded value - ****************************************************/ - - INTEGER fx__dec__Ipv6Packet(BITSTRING &b, LibItsIpv6OverGeoNetworking__TypesAndValues::Ipv6Packet &p) { return -1; } - -} // namespace LibItsIpv6OverGeoNetworking__EncdecDeclarations +#include "LibItsIpv6OverGeoNetworking_EncdecDeclarations.hh" + +namespace LibItsIpv6OverGeoNetworking__EncdecDeclarations { + + /**************************************************** + * @desc External function to encode a Ipv6Packet type + * @param value to encode + * @return encoded value + ****************************************************/ + BITSTRING fx__enc__Ipv6Packet(const LibItsIpv6OverGeoNetworking__TypesAndValues::Ipv6Packet &p) { return int2bit(0, 8); } + + /**************************************************** + * @desc External function to decode a Ipv6Packet type + * @param value to encode + * @return encoded value + ****************************************************/ + + INTEGER fx__dec__Ipv6Packet(BITSTRING &b, LibItsIpv6OverGeoNetworking__TypesAndValues::Ipv6Packet &p) { return -1; } + +} // namespace LibItsIpv6OverGeoNetworking__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsIvim_Encdec.cc b/ccsrc/EncDec/LibItsIvim_Encdec.cc index 9e70906cf076a305bda6face9d9ea28af4bbb920..35c857262fba09447261bc210aead7af916000c6 100644 --- a/ccsrc/EncDec/LibItsIvim_Encdec.cc +++ b/ccsrc/EncDec/LibItsIvim_Encdec.cc @@ -12,7 +12,7 @@ namespace LibItsIvim__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__IvimReq(const LibItsIvim__TestSystem::IvimReq &p_ivimReq) { + BITSTRING fx__enc__IvimReq(const LibItsIvim__TypesAndValues::IvimReq &p_ivimReq) { loggers::get_instance().log_msg(">>> fx__enc__IvimReq: ", p_ivimReq); ivim_codec codec; @@ -30,7 +30,7 @@ namespace LibItsIvim__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__IvimReq(BITSTRING &b, LibItsIvim__TestSystem::IvimReq &p) { + INTEGER fx__dec__IvimReq(BITSTRING &b, LibItsIvim__TypesAndValues::IvimReq &p) { loggers::get_instance().log(">>> fx__dec__IvimReq"); ivim_codec codec; @@ -46,7 +46,7 @@ namespace LibItsIvim__EncdecDeclarations { return 0; } - INTEGER fx__dec__IvimInd(BITSTRING &b, LibItsIvim__TestSystem::IvimInd &p_ivimInd) { + INTEGER fx__dec__IvimInd(BITSTRING &b, LibItsIvim__TypesAndValues::IvimInd &p_ivimInd) { loggers::get_instance().log(">>> fx__dec__IvimInd"); ivim_codec codec; @@ -54,11 +54,11 @@ namespace LibItsIvim__EncdecDeclarations { OCTETSTRING is = bit2oct(b); // Calculate the size of the lower layers information - int s = (LibItsIvim__TestSystem::IvimInd_gnNextHeader_raw_.fieldlength + LibItsIvim__TestSystem::IvimInd_gnHeaderType_raw_.fieldlength + - LibItsIvim__TestSystem::IvimInd_gnHeaderSubtype_raw_.fieldlength + LibItsIvim__TestSystem::IvimInd_gnLifetime_raw_.fieldlength + - LibItsIvim__TestSystem::IvimInd_gnTrafficClass_raw_.fieldlength + LibItsIvim__TestSystem::IvimInd_btpDestinationPort_raw_.fieldlength + - LibItsIvim__TestSystem::IvimInd_btpInfo_raw_.fieldlength + LibItsIvim__TestSystem::IvimInd_ssp_raw_.fieldlength + - LibItsIvim__TestSystem::IvimInd_its__aid_raw_.fieldlength) / + int s = (LibItsIvim__TypesAndValues::IvimInd_gnNextHeader_raw_.fieldlength + LibItsIvim__TypesAndValues::IvimInd_gnHeaderType_raw_.fieldlength + + LibItsIvim__TypesAndValues::IvimInd_gnHeaderSubtype_raw_.fieldlength + LibItsIvim__TypesAndValues::IvimInd_gnLifetime_raw_.fieldlength + + LibItsIvim__TypesAndValues::IvimInd_gnTrafficClass_raw_.fieldlength + LibItsIvim__TypesAndValues::IvimInd_btpDestinationPort_raw_.fieldlength + + LibItsIvim__TypesAndValues::IvimInd_btpInfo_raw_.fieldlength + LibItsIvim__TypesAndValues::IvimInd_ssp_raw_.fieldlength + + LibItsIvim__TypesAndValues::IvimInd_its__aid_raw_.fieldlength) / 8; // Decode CA message if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), ivim) == -1) { @@ -70,91 +70,91 @@ namespace LibItsIvim__EncdecDeclarations { TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_gnNextHeader_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_gnNextHeader_raw_.fieldlength / 8)) { p_ivimInd.gnNextHeader().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsIvim__TestSystem::IvimInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsIvim__TypesAndValues::IvimInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.gnNextHeader() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__IVIM: gnNextHeader=", p_ivimInd.gnNextHeader()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_gnHeaderType_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_gnHeaderType_raw_.fieldlength / 8)) { p_ivimInd.gnHeaderType().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsIvim__TestSystem::IvimInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsIvim__TypesAndValues::IvimInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.gnHeaderType() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__IVIM: gnHeaderType=", p_ivimInd.gnHeaderType()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_gnHeaderSubtype_raw_.fieldlength / 8)) { p_ivimInd.gnHeaderSubtype().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsIvim__TestSystem::IvimInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsIvim__TypesAndValues::IvimInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.gnHeaderSubtype() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__IVIM: gnHeaderSubtype=", p_ivimInd.gnHeaderSubtype()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_gnLifetime_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_gnLifetime_raw_.fieldlength / 8)) { p_ivimInd.gnLifetime().set_to_omit(); } else { INTEGER i; - i.decode(LibItsIvim__TestSystem::IvimInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsIvim__TypesAndValues::IvimInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.gnLifetime() = i; } loggers::get_instance().log_msg("fx__dec__IVIM: gnLifetime=", p_ivimInd.gnLifetime()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_gnTrafficClass_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_gnTrafficClass_raw_.fieldlength / 8)) { p_ivimInd.gnTrafficClass().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsIvim__TestSystem::IvimInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsIvim__TypesAndValues::IvimInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.gnTrafficClass() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__IVIM: gnTrafficClass=", p_ivimInd.gnTrafficClass()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_btpDestinationPort_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_btpDestinationPort_raw_.fieldlength / 8)) { p_ivimInd.btpDestinationPort().set_to_omit(); } else { INTEGER i; - i.decode(LibItsIvim__TestSystem::IvimInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsIvim__TypesAndValues::IvimInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.btpDestinationPort() = i; } loggers::get_instance().log_msg("fx__dec__IVIM: btpDestinationPort=", p_ivimInd.btpDestinationPort()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_btpInfo_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_btpInfo_raw_.fieldlength / 8)) { p_ivimInd.btpInfo().set_to_omit(); } else { INTEGER i; - i.decode(LibItsIvim__TestSystem::IvimInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsIvim__TypesAndValues::IvimInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.btpInfo() = i; } loggers::get_instance().log_msg("fx__dec__IVIM: btpInfo=", p_ivimInd.btpInfo()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_ssp_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_ssp_raw_.fieldlength / 8)) { p_ivimInd.ssp().set_to_omit(); } else { BITSTRING bs; - bs.decode(LibItsIvim__TestSystem::IvimInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + bs.decode(LibItsIvim__TypesAndValues::IvimInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.ssp() = bs; } loggers::get_instance().log_msg("fx__dec__IVIM: ssp=", p_ivimInd.ssp()); loggers::get_instance().log_to_hexa("fx__dec__IVIM: ", decoding_buffer); // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TestSystem::IvimInd_its__aid_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsIvim__TypesAndValues::IvimInd_its__aid_raw_.fieldlength / 8)) { p_ivimInd.its__aid().set_to_omit(); } else { INTEGER i; - i.decode(LibItsIvim__TestSystem::IvimInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsIvim__TypesAndValues::IvimInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ivimInd.its__aid() = i; } loggers::get_instance().log_msg("fx__dec__IVIM: its_aid=", p_ivimInd.its__aid()); diff --git a/ccsrc/EncDec/LibItsMapemSpatem_Encdec.cc b/ccsrc/EncDec/LibItsMapemSpatem_Encdec.cc index 7ee0826f6f383f2fd678fdfe0dd58592fb8031c4..737ab2d8125897eabab120a355d7237b84f17d31 100644 --- a/ccsrc/EncDec/LibItsMapemSpatem_Encdec.cc +++ b/ccsrc/EncDec/LibItsMapemSpatem_Encdec.cc @@ -13,7 +13,7 @@ namespace LibItsMapemSpatem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__MapemReq(const LibItsMapemSpatem__TestSystem::MapemReq &p_sremReq) { + BITSTRING fx__enc__MapemReq(const LibItsMapemSpatem__TypesAndValues::MapemReq &p_sremReq) { loggers::get_instance().log_msg(">>> fx__enc__MapemReq: ", p_sremReq); mapem_codec codec; @@ -31,7 +31,7 @@ namespace LibItsMapemSpatem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__MapemReq(BITSTRING &b, LibItsMapemSpatem__TestSystem::MapemReq &p) { + INTEGER fx__dec__MapemReq(BITSTRING &b, LibItsMapemSpatem__TypesAndValues::MapemReq &p) { loggers::get_instance().log(">>> fx__dec__MapemReq"); mapem_codec codec; @@ -47,7 +47,7 @@ namespace LibItsMapemSpatem__EncdecDeclarations { return 0; } - INTEGER fx__dec__MapemInd(BITSTRING &b, LibItsMapemSpatem__TestSystem::MapemInd &p_mapemInd) { + INTEGER fx__dec__MapemInd(BITSTRING &b, LibItsMapemSpatem__TypesAndValues::MapemInd &p_mapemInd) { loggers::get_instance().log(">>> fx__dec__MapemInd"); mapem_codec codec; @@ -55,11 +55,11 @@ namespace LibItsMapemSpatem__EncdecDeclarations { OCTETSTRING is = bit2oct(b); // Calculate the size of the lower layers information - int s = (LibItsMapemSpatem__TestSystem::MapemInd_gnNextHeader_raw_.fieldlength + LibItsMapemSpatem__TestSystem::MapemInd_gnHeaderType_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::MapemInd_gnHeaderSubtype_raw_.fieldlength + LibItsMapemSpatem__TestSystem::MapemInd_gnLifetime_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::MapemInd_gnTrafficClass_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::MapemInd_btpDestinationPort_raw_.fieldlength + LibItsMapemSpatem__TestSystem::MapemInd_btpInfo_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::MapemInd_ssp_raw_.fieldlength + LibItsMapemSpatem__TestSystem::MapemInd_its__aid_raw_.fieldlength) / + int s = (LibItsMapemSpatem__TypesAndValues::MapemInd_gnNextHeader_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::MapemInd_gnHeaderType_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::MapemInd_gnHeaderSubtype_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::MapemInd_gnLifetime_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::MapemInd_gnTrafficClass_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::MapemInd_btpDestinationPort_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::MapemInd_btpInfo_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::MapemInd_ssp_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::MapemInd_its__aid_raw_.fieldlength) / 8; // Decode CA message if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), mapem) == -1) { @@ -71,91 +71,91 @@ namespace LibItsMapemSpatem__EncdecDeclarations { TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); loggers::get_instance().log_to_hexa("fx__dec__MapemInd: ", decoding_buffer); // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_gnNextHeader_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_gnNextHeader_raw_.fieldlength / 8)) { p_mapemInd.gnNextHeader().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::MapemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnNextHeader() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__MapemInd: gnNextHeader=", p_mapemInd.gnNextHeader()); loggers::get_instance().log_to_hexa("fx__dec__MapemInd: ", decoding_buffer); // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_gnHeaderType_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_gnHeaderType_raw_.fieldlength / 8)) { p_mapemInd.gnHeaderType().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::MapemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnHeaderType() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__Mapem: gnHeaderType=", p_mapemInd.gnHeaderType()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { p_mapemInd.gnHeaderSubtype().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::MapemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnHeaderSubtype() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__Mapem: gnHeaderSubtype=", p_mapemInd.gnHeaderSubtype()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_gnLifetime_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_gnLifetime_raw_.fieldlength / 8)) { p_mapemInd.gnLifetime().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::MapemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnLifetime() = i; } loggers::get_instance().log_msg("fx__dec__Mapem: gnLifetime=", p_mapemInd.gnLifetime()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_gnTrafficClass_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_gnTrafficClass_raw_.fieldlength / 8)) { p_mapemInd.gnTrafficClass().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::MapemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnTrafficClass() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__Mapem: gnTrafficClass=", p_mapemInd.gnTrafficClass()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_btpDestinationPort_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_btpDestinationPort_raw_.fieldlength / 8)) { p_mapemInd.btpDestinationPort().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::MapemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.btpDestinationPort() = i; } loggers::get_instance().log_msg("fx__dec__Mapem: btpDestinationPort=", p_mapemInd.btpDestinationPort()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_btpInfo_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_btpInfo_raw_.fieldlength / 8)) { p_mapemInd.btpInfo().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::MapemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.btpInfo() = i; } loggers::get_instance().log_msg("fx__dec__Mapem: btpInfo=", p_mapemInd.btpInfo()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_ssp_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_ssp_raw_.fieldlength / 8)) { p_mapemInd.ssp().set_to_omit(); } else { BITSTRING bs; - bs.decode(LibItsMapemSpatem__TestSystem::MapemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + bs.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.ssp() = bs; } loggers::get_instance().log_msg("fx__dec__Mapem: ssp=", p_mapemInd.ssp()); loggers::get_instance().log_to_hexa("fx__dec__Mapem: ", decoding_buffer); // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::MapemInd_its__aid_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::MapemInd_its__aid_raw_.fieldlength / 8)) { p_mapemInd.its__aid().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::MapemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::MapemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.its__aid() = i; } loggers::get_instance().log_msg("fx__dec__Mapem: its_aid=", p_mapemInd.its__aid()); @@ -191,7 +191,7 @@ namespace LibItsMapemSpatem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__SpatemReq(const LibItsMapemSpatem__TestSystem::SpatemReq &p_spatemReq) { + BITSTRING fx__enc__SpatemReq(const LibItsMapemSpatem__TypesAndValues::SpatemReq &p_spatemReq) { loggers::get_instance().log_msg(">>> fx__enc__SpatemReq: ", p_spatemReq); spatem_codec codec; @@ -209,7 +209,7 @@ namespace LibItsMapemSpatem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__SpatemReq(BITSTRING &b, LibItsMapemSpatem__TestSystem::SpatemReq &p) { + INTEGER fx__dec__SpatemReq(BITSTRING &b, LibItsMapemSpatem__TypesAndValues::SpatemReq &p) { loggers::get_instance().log(">>> fx__dec__SpatemReq"); spatem_codec codec; @@ -225,7 +225,7 @@ namespace LibItsMapemSpatem__EncdecDeclarations { return 0; } - INTEGER fx__dec__SpatemInd(BITSTRING &b, LibItsMapemSpatem__TestSystem::SpatemInd &p_mapemInd) { + INTEGER fx__dec__SpatemInd(BITSTRING &b, LibItsMapemSpatem__TypesAndValues::SpatemInd &p_mapemInd) { loggers::get_instance().log(">>> fx__dec__SpatemInd"); spatem_codec codec; @@ -233,11 +233,11 @@ namespace LibItsMapemSpatem__EncdecDeclarations { OCTETSTRING is = bit2oct(b); // Calculate the size of the lower layers information - int s = (LibItsMapemSpatem__TestSystem::SpatemInd_gnNextHeader_raw_.fieldlength + LibItsMapemSpatem__TestSystem::SpatemInd_gnHeaderType_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::SpatemInd_gnHeaderSubtype_raw_.fieldlength + LibItsMapemSpatem__TestSystem::SpatemInd_gnLifetime_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::SpatemInd_gnTrafficClass_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::SpatemInd_btpDestinationPort_raw_.fieldlength + LibItsMapemSpatem__TestSystem::SpatemInd_btpInfo_raw_.fieldlength + - LibItsMapemSpatem__TestSystem::SpatemInd_ssp_raw_.fieldlength + LibItsMapemSpatem__TestSystem::SpatemInd_its__aid_raw_.fieldlength) / + int s = (LibItsMapemSpatem__TypesAndValues::SpatemInd_gnNextHeader_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::SpatemInd_gnHeaderType_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::SpatemInd_gnHeaderSubtype_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::SpatemInd_gnLifetime_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::SpatemInd_gnTrafficClass_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::SpatemInd_btpDestinationPort_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::SpatemInd_btpInfo_raw_.fieldlength + + LibItsMapemSpatem__TypesAndValues::SpatemInd_ssp_raw_.fieldlength + LibItsMapemSpatem__TypesAndValues::SpatemInd_its__aid_raw_.fieldlength) / 8; // Decode CA message if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), spatem) == -1) { @@ -249,91 +249,91 @@ namespace LibItsMapemSpatem__EncdecDeclarations { TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); loggers::get_instance().log_to_hexa("fx__dec__SpatemInd: ", decoding_buffer); // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_gnNextHeader_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnNextHeader_raw_.fieldlength / 8)) { p_mapemInd.gnNextHeader().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::SpatemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnNextHeader() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SpatemInd: gnNextHeader=", p_mapemInd.gnNextHeader()); loggers::get_instance().log_to_hexa("fx__dec__SpatemInd: ", decoding_buffer); // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_gnHeaderType_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnHeaderType_raw_.fieldlength / 8)) { p_mapemInd.gnHeaderType().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::SpatemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnHeaderType() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__Spatem: gnHeaderType=", p_mapemInd.gnHeaderType()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { p_mapemInd.gnHeaderSubtype().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::SpatemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnHeaderSubtype() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__Spatem: gnHeaderSubtype=", p_mapemInd.gnHeaderSubtype()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_gnLifetime_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnLifetime_raw_.fieldlength / 8)) { p_mapemInd.gnLifetime().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::SpatemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnLifetime() = i; } loggers::get_instance().log_msg("fx__dec__Spatem: gnLifetime=", p_mapemInd.gnLifetime()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_gnTrafficClass_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnTrafficClass_raw_.fieldlength / 8)) { p_mapemInd.gnTrafficClass().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsMapemSpatem__TestSystem::SpatemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.gnTrafficClass() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__Spatem: gnTrafficClass=", p_mapemInd.gnTrafficClass()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_btpDestinationPort_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_btpDestinationPort_raw_.fieldlength / 8)) { p_mapemInd.btpDestinationPort().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::SpatemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.btpDestinationPort() = i; } loggers::get_instance().log_msg("fx__dec__Spatem: btpDestinationPort=", p_mapemInd.btpDestinationPort()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_btpInfo_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_btpInfo_raw_.fieldlength / 8)) { p_mapemInd.btpInfo().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::SpatemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.btpInfo() = i; } loggers::get_instance().log_msg("fx__dec__Spatem: btpInfo=", p_mapemInd.btpInfo()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_ssp_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_ssp_raw_.fieldlength / 8)) { p_mapemInd.ssp().set_to_omit(); } else { BITSTRING bs; - bs.decode(LibItsMapemSpatem__TestSystem::SpatemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + bs.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.ssp() = bs; } loggers::get_instance().log_msg("fx__dec__Spatem: ssp=", p_mapemInd.ssp()); loggers::get_instance().log_to_hexa("fx__dec__Spatem: ", decoding_buffer); // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TestSystem::SpatemInd_its__aid_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsMapemSpatem__TypesAndValues::SpatemInd_its__aid_raw_.fieldlength / 8)) { p_mapemInd.its__aid().set_to_omit(); } else { INTEGER i; - i.decode(LibItsMapemSpatem__TestSystem::SpatemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsMapemSpatem__TypesAndValues::SpatemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_mapemInd.its__aid() = i; } loggers::get_instance().log_msg("fx__dec__Spatem: its_aid=", p_mapemInd.its__aid()); diff --git a/ccsrc/EncDec/LibItsPki_Encdec.cc b/ccsrc/EncDec/LibItsPki_Encdec.cc index c13057ef1e15d874ceea99aec5ff35379a180175..90391c8b19163d6cf73bc1160182274380104208 100644 --- a/ccsrc/EncDec/LibItsPki_Encdec.cc +++ b/ccsrc/EncDec/LibItsPki_Encdec.cc @@ -1,384 +1,384 @@ -#include "LibItsPki_EncdecDeclarations.hh" - -#include "etsi_ts102941_base_types_public_keys.hh" -#include "etsi_ts102941_data_codec.hh" -#include "etsi_ts102941_data_content_codec.hh" -#include "etsi_ts102941_types_authorization_inner_request.hh" -#include "etsi_ts102941_types_authorization_inner_response.hh" -#include "etsi_ts102941_types_authorization_shared_at_request.hh" -#include "etsi_ts102941_types_authorization_validation_request.hh" -#include "etsi_ts102941_types_authorization_validation_response.hh" -#include "etsi_ts102941_types_enrolment_inner_request.hh" -#include "etsi_ts102941_types_enrolment_inner_response.hh" -#include "ieee_1609dot2_base_types_public_encryption_key.hh" -#include "ieee_1609dot2_base_types_public_verification_key.hh" - -#include "etsi_ts102941_trust_lists_ctl_format.hh" - -#include "loggers.hh" - -//#include "cam_pdu_codec.hh" -//#include "codec.hh" - -namespace LibItsPki__EncdecDeclarations { - - /*BITSTRING fx__enc__CAM(const CAM__PDU__Descriptions::CAM &p_cam) { - cam_pdu_codec asn_codec; - BITSTRING b; - int rc = asn_codec.encode(p_cam, b); - if (rc) { - return b; - } - return int2bit(0, 1); - }*/ - - BITSTRING fx__enc__EtsiTs102941Data(const EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data) { - loggers::get_instance().log_msg(">>> fx__enc__EtsiTs102941Data: ", p_etsi_ts_102941_data); - - etsi_ts102941_data_codec codec; - OCTETSTRING os; - if (codec.encode(p_etsi_ts_102941_data, os) == -1) { - loggers::get_instance().warning("fx__enc__EtsiTs102941Data: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__EtsiTs102941Data(BITSTRING &b, EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data) { - loggers::get_instance().log_msg(">>> fx__dec__EtsiTs102941Data: ", b); - - etsi_ts102941_data_codec codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_etsi_ts_102941_data) == -1) { - loggers::get_instance().warning("fx__dec__EtsiTs102941Data: -1 result code was returned"); - return -1; - } - - return 0; - } - - BITSTRING fx__enc__EtsiTs102941DataContent(const EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_102941_data_content) { - loggers::get_instance().log_msg(">>> fx__enc__EtsiTs102941DataContent: ", p_etsi_ts_102941_data_content); - - etsi_ts102941_data_content_codec codec; - OCTETSTRING os; - if (codec.encode(p_etsi_ts_102941_data_content, os) == -1) { - loggers::get_instance().warning("fx__enc__EtsiTs102941DataContent: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__EtsiTs102941DataContent(BITSTRING &b, EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_102941_data_content) { - loggers::get_instance().log_msg(">>> fx__dec__EtsiTs102941DataContent: ", b); - - etsi_ts102941_data_content_codec codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_etsi_ts_102941_data_content) == -1) { - loggers::get_instance().warning("fx__dec__EtsiTs102941DataContent: -1 result code was returned"); - return -1; - } - - return 0; - } - - BITSTRING fx__enc__InnerEcRequest(const EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request) { - loggers::get_instance().log_msg(">>> fx_enc_InnerEcRequest: ", p_inner_request); - - etsi_ts102941_types_enrolment_inner_request codec; - OCTETSTRING os; - if (codec.encode(p_inner_request, os) == -1) { - loggers::get_instance().warning("fx_enc_InnerEcRequest: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__InnerEcRequest(BITSTRING &b, EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request) { - loggers::get_instance().log_msg(">>> fx__dec__InnerEcRequest: ", b); - - etsi_ts102941_types_enrolment_inner_request codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_inner_request) == -1) { - loggers::get_instance().warning("fx__dec__InnerEcRequest: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__InnerEcRequest: ", p_inner_request); - return 0; - } - - BITSTRING fx__enc__InnerEcResponse(const EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response) { - loggers::get_instance().log_msg(">>> fx__enc__InnerEcResponse: ", p_inner_response); - - etsi_ts102941_types_enrolment_inner_response codec; - OCTETSTRING os; - if (codec.encode(p_inner_response, os) == -1) { - loggers::get_instance().warning("fx__enc__InnerEcResponse: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__InnerEcResponse(BITSTRING &b, EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response) { - loggers::get_instance().log_msg(">>> fx__dec__InnerEcResponse: ", b); - - etsi_ts102941_types_enrolment_inner_response codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_inner_response) == -1) { - loggers::get_instance().warning("fx__dec__InnerEcResponse: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__InnerEcResponse: ", p_inner_response); - return 0; - } - - BITSTRING fx__enc__InnerAtRequest(const EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request) { - loggers::get_instance().log_msg(">>> fx_enc_InnerAtRequest: ", p_inner_request); - - etsi_ts102941_types_authorization_inner_request codec; - OCTETSTRING os; - if (codec.encode(p_inner_request, os) == -1) { - loggers::get_instance().warning("fx_enc_InnerAtRequest: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__InnerAtRequest(BITSTRING &b, EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request) { - loggers::get_instance().log_msg(">>> fx__dec__InnerAtRequest: ", b); - - etsi_ts102941_types_authorization_inner_request codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_inner_request) == -1) { - loggers::get_instance().warning("fx__dec__InnerAtRequest: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__InnerAtRequest: ", p_inner_request); - return 0; - } - - BITSTRING fx__enc__InnerAtResponse(const EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response) { - loggers::get_instance().log_msg(">>> fx__enc__InnerAtResponse: ", p_inner_response); - - etsi_ts102941_types_authorization_inner_response codec; - OCTETSTRING os; - if (codec.encode(p_inner_response, os) == -1) { - loggers::get_instance().warning("fx__enc__InnerAtResponse: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__InnerAtResponse(BITSTRING &b, EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response) { - loggers::get_instance().log_msg(">>> fx__dec__InnerAtResponse: ", b); - - etsi_ts102941_types_authorization_inner_response codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_inner_response) == -1) { - loggers::get_instance().warning("fx__dec__InnerAtResponse: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__InnerAtResponse: ", p_inner_response); - return 0; - } - - BITSTRING fx__enc__SharedAtRequest(EtsiTs102941TypesAuthorization::SharedAtRequest const &p_shared_at) { - loggers::get_instance().log_msg(">>> fx__enc__SharedAtRequest: ", p_shared_at); - - etsi_ts102941_types_authorization_shared_at_request codec; - OCTETSTRING os; - if (codec.encode(p_shared_at, os) == -1) { - loggers::get_instance().warning("fx__enc__SharedAtRequest: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__SharedAtRequest(BITSTRING &b, EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at) { - loggers::get_instance().log_msg(">>> fx__dec__SharedAtRequest: ", b); - - etsi_ts102941_types_authorization_shared_at_request codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_shared_at) == -1) { - loggers::get_instance().warning("fx__dec__SharedAtRequest: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__SharedAtRequest: ", p_shared_at); - return 0; - } - - BITSTRING fx__enc__AuthorizationValidationRequest(EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest const &p_shared_at) { - loggers::get_instance().log_msg(">>> fx__enc__AuthorizationValidationRequest: ", p_shared_at); - - etsi_ts102941_types_authorization_validation_request codec; - OCTETSTRING os; - if (codec.encode(p_shared_at, os) == -1) { - loggers::get_instance().warning("fx__enc__AuthorizationValidationRequest: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__AuthorizationValidationRequest(BITSTRING &b, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_shared_at) { - loggers::get_instance().log_msg(">>> fx__dec__AuthorizationValidationRequest: ", b); - - etsi_ts102941_types_authorization_validation_request codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_shared_at) == -1) { - loggers::get_instance().warning("fx__dec__AuthorizationValidationRequest: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__AuthorizationValidationRequest: ", p_shared_at); - return 0; - } - - BITSTRING fx__enc__AuthorizationValidationResponse(EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse const &p_shared_at) { - loggers::get_instance().log_msg(">>> fx__enc__AuthorizationValidationResponse: ", p_shared_at); - - etsi_ts102941_types_authorization_validation_response codec; - OCTETSTRING os; - if (codec.encode(p_shared_at, os) == -1) { - loggers::get_instance().warning("fx__enc__AuthorizationValidationResponse: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__AuthorizationValidationResponse(BITSTRING &b, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_shared_at) { - loggers::get_instance().log_msg(">>> fx__dec__AuthorizationValidationResponse: ", b); - - etsi_ts102941_types_authorization_validation_response codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_shared_at) == -1) { - loggers::get_instance().warning("fx__dec__AuthorizationValidationResponse: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__AuthorizationValidationResponse: ", p_shared_at); - return 0; - } - - BITSTRING fx__enc__PublicKeys(EtsiTs102941BaseTypes::PublicKeys const &p_public_keys) { - loggers::get_instance().log_msg(">>> fx__enc__PublicKeys: ", p_public_keys); - - etsi_ts102941_base_types_public_keys codec; - OCTETSTRING os; - if (codec.encode(p_public_keys, os) == -1) { - loggers::get_instance().warning("fx__enc__PublicKeys: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__PublicKeys(BITSTRING &b, EtsiTs102941BaseTypes::PublicKeys &p_public_keys) { - loggers::get_instance().log_msg(">>> fx__dec__PublicKeys: ", b); - - etsi_ts102941_base_types_public_keys codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_public_keys) == -1) { - loggers::get_instance().warning("fx__dec__PublicKeys: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__PublicKeys: ", p_public_keys); - return 0; - } - - BITSTRING fx__enc__PublicVerificationKey(Ieee1609Dot2BaseTypes::PublicVerificationKey const &p_public_verification_key) { - loggers::get_instance().log_msg(">>> fx__enc__PublicVerificationKey: ", p_public_verification_key); - - ieee_1609dot2_base_types_public_verification_key codec; - OCTETSTRING os; - if (codec.encode(p_public_verification_key, os) == -1) { - loggers::get_instance().warning("fx__enc__PublicVerificationKey: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__PublicVerificationKey(BITSTRING &b, Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key) { - loggers::get_instance().log_msg(">>> fx__dec__PublicVerificationKey: ", b); - - ieee_1609dot2_base_types_public_verification_key codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_public_verification_key) == -1) { - loggers::get_instance().warning("fx__dec__PublicVerificationKey: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__PublicVerificationKey: ", p_public_verification_key); - return 0; - } - - BITSTRING fx__enc__PublicEncryptionKey(Ieee1609Dot2BaseTypes::PublicEncryptionKey const &p_public_encryption_key) { - loggers::get_instance().log_msg(">>> fx__enc__PublicEncryptionKey: ", p_public_encryption_key); - - ieee_1609dot2_base_types_public_encryption_key codec; - OCTETSTRING os; - if (codec.encode(p_public_encryption_key, os) == -1) { - loggers::get_instance().warning("fx__enc__PublicEncryptionKey: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__PublicEncryptionKey(BITSTRING &b, Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key) { - loggers::get_instance().log_msg(">>> fx__dec__PublicEncryptionKey: ", b); - - ieee_1609dot2_base_types_public_encryption_key codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_public_encryption_key) == -1) { - loggers::get_instance().warning("fx__dec__PublicEncryptionKey: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__PublicEncryptionKey: ", p_public_encryption_key); - return 0; - } - - BITSTRING fx__enc__CtlFormat(EtsiTs102941TrustLists::CtlFormat const &p_ctl_format) { - loggers::get_instance().log_msg(">>> fx__enc__CtlFormat: ", p_ctl_format); - - etsi_ts102941_trust_lists_ctl_format codec; - OCTETSTRING os; - if (codec.encode(p_ctl_format, os) == -1) { - loggers::get_instance().warning("fx__enc__CtlFormat: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__CtlFormat(BITSTRING &b, EtsiTs102941TrustLists::CtlFormat &p_ctl_format) { - loggers::get_instance().log_msg(">>> fx__dec__CtlFormat: ", b); - - etsi_ts102941_trust_lists_ctl_format codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_ctl_format) == -1) { - loggers::get_instance().warning("fx__dec__CtlFormat: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__CtlFormat: ", p_ctl_format); - return 0; - } - -} // End of namespace LibItsPki__EncdecDeclarations +#include "LibItsPki_EncdecDeclarations.hh" + +#include "etsi_ts102941_base_types_public_keys.hh" +#include "etsi_ts102941_data_codec.hh" +#include "etsi_ts102941_data_content_codec.hh" +#include "etsi_ts102941_types_authorization_inner_request.hh" +#include "etsi_ts102941_types_authorization_inner_response.hh" +#include "etsi_ts102941_types_authorization_shared_at_request.hh" +#include "etsi_ts102941_types_authorization_validation_request.hh" +#include "etsi_ts102941_types_authorization_validation_response.hh" +#include "etsi_ts102941_types_enrolment_inner_request.hh" +#include "etsi_ts102941_types_enrolment_inner_response.hh" +#include "ieee_1609dot2_base_types_public_encryption_key.hh" +#include "ieee_1609dot2_base_types_public_verification_key.hh" + +#include "etsi_ts102941_trust_lists_ctl_format.hh" + +#include "loggers.hh" + +//#include "cam_pdu_codec.hh" +//#include "codec.hh" + +namespace LibItsPki__EncdecDeclarations { + + /*BITSTRING fx__enc__CAM(const CAM__PDU__Descriptions::CAM &p_cam) { + cam_pdu_codec asn_codec; + BITSTRING b; + int rc = asn_codec.encode(p_cam, b); + if (rc) { + return b; + } + return int2bit(0, 1); + }*/ + + BITSTRING fx__enc__EtsiTs102941Data(const EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data) { + loggers::get_instance().log_msg(">>> fx__enc__EtsiTs102941Data: ", p_etsi_ts_102941_data); + + etsi_ts102941_data_codec codec; + OCTETSTRING os; + if (codec.encode(p_etsi_ts_102941_data, os) == -1) { + loggers::get_instance().warning("fx__enc__EtsiTs102941Data: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__EtsiTs102941Data(BITSTRING &b, EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data) { + loggers::get_instance().log_msg(">>> fx__dec__EtsiTs102941Data: ", b); + + etsi_ts102941_data_codec codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_etsi_ts_102941_data) == -1) { + loggers::get_instance().warning("fx__dec__EtsiTs102941Data: -1 result code was returned"); + return -1; + } + + return 0; + } + + BITSTRING fx__enc__EtsiTs102941DataContent(const EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_102941_data_content) { + loggers::get_instance().log_msg(">>> fx__enc__EtsiTs102941DataContent: ", p_etsi_ts_102941_data_content); + + etsi_ts102941_data_content_codec codec; + OCTETSTRING os; + if (codec.encode(p_etsi_ts_102941_data_content, os) == -1) { + loggers::get_instance().warning("fx__enc__EtsiTs102941DataContent: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__EtsiTs102941DataContent(BITSTRING &b, EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_102941_data_content) { + loggers::get_instance().log_msg(">>> fx__dec__EtsiTs102941DataContent: ", b); + + etsi_ts102941_data_content_codec codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_etsi_ts_102941_data_content) == -1) { + loggers::get_instance().warning("fx__dec__EtsiTs102941DataContent: -1 result code was returned"); + return -1; + } + + return 0; + } + + BITSTRING fx__enc__InnerEcRequest(const EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request) { + loggers::get_instance().log_msg(">>> fx_enc_InnerEcRequest: ", p_inner_request); + + etsi_ts102941_types_enrolment_inner_request codec; + OCTETSTRING os; + if (codec.encode(p_inner_request, os) == -1) { + loggers::get_instance().warning("fx_enc_InnerEcRequest: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__InnerEcRequest(BITSTRING &b, EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request) { + loggers::get_instance().log_msg(">>> fx__dec__InnerEcRequest: ", b); + + etsi_ts102941_types_enrolment_inner_request codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_inner_request) == -1) { + loggers::get_instance().warning("fx__dec__InnerEcRequest: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__InnerEcRequest: ", p_inner_request); + return 0; + } + + BITSTRING fx__enc__InnerEcResponse(const EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response) { + loggers::get_instance().log_msg(">>> fx__enc__InnerEcResponse: ", p_inner_response); + + etsi_ts102941_types_enrolment_inner_response codec; + OCTETSTRING os; + if (codec.encode(p_inner_response, os) == -1) { + loggers::get_instance().warning("fx__enc__InnerEcResponse: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__InnerEcResponse(BITSTRING &b, EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response) { + loggers::get_instance().log_msg(">>> fx__dec__InnerEcResponse: ", b); + + etsi_ts102941_types_enrolment_inner_response codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_inner_response) == -1) { + loggers::get_instance().warning("fx__dec__InnerEcResponse: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__InnerEcResponse: ", p_inner_response); + return 0; + } + + BITSTRING fx__enc__InnerAtRequest(const EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request) { + loggers::get_instance().log_msg(">>> fx_enc_InnerAtRequest: ", p_inner_request); + + etsi_ts102941_types_authorization_inner_request codec; + OCTETSTRING os; + if (codec.encode(p_inner_request, os) == -1) { + loggers::get_instance().warning("fx_enc_InnerAtRequest: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__InnerAtRequest(BITSTRING &b, EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request) { + loggers::get_instance().log_msg(">>> fx__dec__InnerAtRequest: ", b); + + etsi_ts102941_types_authorization_inner_request codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_inner_request) == -1) { + loggers::get_instance().warning("fx__dec__InnerAtRequest: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__InnerAtRequest: ", p_inner_request); + return 0; + } + + BITSTRING fx__enc__InnerAtResponse(const EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response) { + loggers::get_instance().log_msg(">>> fx__enc__InnerAtResponse: ", p_inner_response); + + etsi_ts102941_types_authorization_inner_response codec; + OCTETSTRING os; + if (codec.encode(p_inner_response, os) == -1) { + loggers::get_instance().warning("fx__enc__InnerAtResponse: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__InnerAtResponse(BITSTRING &b, EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response) { + loggers::get_instance().log_msg(">>> fx__dec__InnerAtResponse: ", b); + + etsi_ts102941_types_authorization_inner_response codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_inner_response) == -1) { + loggers::get_instance().warning("fx__dec__InnerAtResponse: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__InnerAtResponse: ", p_inner_response); + return 0; + } + + BITSTRING fx__enc__SharedAtRequest(EtsiTs102941TypesAuthorization::SharedAtRequest const &p_shared_at) { + loggers::get_instance().log_msg(">>> fx__enc__SharedAtRequest: ", p_shared_at); + + etsi_ts102941_types_authorization_shared_at_request codec; + OCTETSTRING os; + if (codec.encode(p_shared_at, os) == -1) { + loggers::get_instance().warning("fx__enc__SharedAtRequest: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__SharedAtRequest(BITSTRING &b, EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at) { + loggers::get_instance().log_msg(">>> fx__dec__SharedAtRequest: ", b); + + etsi_ts102941_types_authorization_shared_at_request codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_shared_at) == -1) { + loggers::get_instance().warning("fx__dec__SharedAtRequest: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__SharedAtRequest: ", p_shared_at); + return 0; + } + + BITSTRING fx__enc__AuthorizationValidationRequest(EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest const &p_shared_at) { + loggers::get_instance().log_msg(">>> fx__enc__AuthorizationValidationRequest: ", p_shared_at); + + etsi_ts102941_types_authorization_validation_request codec; + OCTETSTRING os; + if (codec.encode(p_shared_at, os) == -1) { + loggers::get_instance().warning("fx__enc__AuthorizationValidationRequest: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__AuthorizationValidationRequest(BITSTRING &b, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_shared_at) { + loggers::get_instance().log_msg(">>> fx__dec__AuthorizationValidationRequest: ", b); + + etsi_ts102941_types_authorization_validation_request codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_shared_at) == -1) { + loggers::get_instance().warning("fx__dec__AuthorizationValidationRequest: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__AuthorizationValidationRequest: ", p_shared_at); + return 0; + } + + BITSTRING fx__enc__AuthorizationValidationResponse(EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse const &p_shared_at) { + loggers::get_instance().log_msg(">>> fx__enc__AuthorizationValidationResponse: ", p_shared_at); + + etsi_ts102941_types_authorization_validation_response codec; + OCTETSTRING os; + if (codec.encode(p_shared_at, os) == -1) { + loggers::get_instance().warning("fx__enc__AuthorizationValidationResponse: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__AuthorizationValidationResponse(BITSTRING &b, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_shared_at) { + loggers::get_instance().log_msg(">>> fx__dec__AuthorizationValidationResponse: ", b); + + etsi_ts102941_types_authorization_validation_response codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_shared_at) == -1) { + loggers::get_instance().warning("fx__dec__AuthorizationValidationResponse: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__AuthorizationValidationResponse: ", p_shared_at); + return 0; + } + + BITSTRING fx__enc__PublicKeys(EtsiTs102941BaseTypes::PublicKeys const &p_public_keys) { + loggers::get_instance().log_msg(">>> fx__enc__PublicKeys: ", p_public_keys); + + etsi_ts102941_base_types_public_keys codec; + OCTETSTRING os; + if (codec.encode(p_public_keys, os) == -1) { + loggers::get_instance().warning("fx__enc__PublicKeys: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__PublicKeys(BITSTRING &b, EtsiTs102941BaseTypes::PublicKeys &p_public_keys) { + loggers::get_instance().log_msg(">>> fx__dec__PublicKeys: ", b); + + etsi_ts102941_base_types_public_keys codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_public_keys) == -1) { + loggers::get_instance().warning("fx__dec__PublicKeys: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__PublicKeys: ", p_public_keys); + return 0; + } + + BITSTRING fx__enc__PublicVerificationKey(Ieee1609Dot2BaseTypes::PublicVerificationKey const &p_public_verification_key) { + loggers::get_instance().log_msg(">>> fx__enc__PublicVerificationKey: ", p_public_verification_key); + + ieee_1609dot2_base_types_public_verification_key codec; + OCTETSTRING os; + if (codec.encode(p_public_verification_key, os) == -1) { + loggers::get_instance().warning("fx__enc__PublicVerificationKey: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__PublicVerificationKey(BITSTRING &b, Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key) { + loggers::get_instance().log_msg(">>> fx__dec__PublicVerificationKey: ", b); + + ieee_1609dot2_base_types_public_verification_key codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_public_verification_key) == -1) { + loggers::get_instance().warning("fx__dec__PublicVerificationKey: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__PublicVerificationKey: ", p_public_verification_key); + return 0; + } + + BITSTRING fx__enc__PublicEncryptionKey(Ieee1609Dot2BaseTypes::PublicEncryptionKey const &p_public_encryption_key) { + loggers::get_instance().log_msg(">>> fx__enc__PublicEncryptionKey: ", p_public_encryption_key); + + ieee_1609dot2_base_types_public_encryption_key codec; + OCTETSTRING os; + if (codec.encode(p_public_encryption_key, os) == -1) { + loggers::get_instance().warning("fx__enc__PublicEncryptionKey: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__PublicEncryptionKey(BITSTRING &b, Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key) { + loggers::get_instance().log_msg(">>> fx__dec__PublicEncryptionKey: ", b); + + ieee_1609dot2_base_types_public_encryption_key codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_public_encryption_key) == -1) { + loggers::get_instance().warning("fx__dec__PublicEncryptionKey: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__PublicEncryptionKey: ", p_public_encryption_key); + return 0; + } + + BITSTRING fx__enc__CtlFormat(EtsiTs102941TrustLists::CtlFormat const &p_ctl_format) { + loggers::get_instance().log_msg(">>> fx__enc__CtlFormat: ", p_ctl_format); + + etsi_ts102941_trust_lists_ctl_format codec; + OCTETSTRING os; + if (codec.encode(p_ctl_format, os) == -1) { + loggers::get_instance().warning("fx__enc__CtlFormat: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__CtlFormat(BITSTRING &b, EtsiTs102941TrustLists::CtlFormat &p_ctl_format) { + loggers::get_instance().log_msg(">>> fx__dec__CtlFormat: ", b); + + etsi_ts102941_trust_lists_ctl_format codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_ctl_format) == -1) { + loggers::get_instance().warning("fx__dec__CtlFormat: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__CtlFormat: ", p_ctl_format); + return 0; + } + +} // End of namespace LibItsPki__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsRtcmem_Encdec.cc b/ccsrc/EncDec/LibItsRtcmem_Encdec.cc index 2b3227180fc6d0f222c0cae3bcdc185bf111d0d8..d1c722fc5f9e3980c20ca5596a6378b8b8f1d247 100644 --- a/ccsrc/EncDec/LibItsRtcmem_Encdec.cc +++ b/ccsrc/EncDec/LibItsRtcmem_Encdec.cc @@ -12,7 +12,7 @@ namespace LibItsRtcmem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__RtcmemReq(const LibItsRtcmem__TestSystem::RtcmemReq &p_rtcmemReq) { + BITSTRING fx__enc__RtcmemReq(const LibItsRtcmem__TypesAndValues::RtcmemReq &p_rtcmemReq) { loggers::get_instance().log_msg(">>> fx__enc__RtcmemReq: ", p_rtcmemReq); RtcmemCodec codec; @@ -30,7 +30,7 @@ namespace LibItsRtcmem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__RtcmemReq(BITSTRING &b, LibItsRtcmem__TestSystem::RtcmemReq &p) { + INTEGER fx__dec__RtcmemReq(BITSTRING &b, LibItsRtcmem__TypesAndValues::RtcmemReq &p) { loggers::get_instance().log(">>> fx__dec__RtcmemReq"); RtcmemCodec codec; @@ -46,7 +46,7 @@ namespace LibItsRtcmem__EncdecDeclarations { return 0; } - INTEGER fx__dec__RtcmemInd(BITSTRING &b, LibItsRtcmem__TestSystem::RtcmemInd &p_rtcmemInd) { + INTEGER fx__dec__RtcmemInd(BITSTRING &b, LibItsRtcmem__TypesAndValues::RtcmemInd &p_rtcmemInd) { loggers::get_instance().log(">>> fx__dec__RtcmemInd"); RtcmemCodec codec; @@ -54,11 +54,11 @@ namespace LibItsRtcmem__EncdecDeclarations { OCTETSTRING is = bit2oct(b); // Calculate the size of the lower layers information - int s = (LibItsRtcmem__TestSystem::RtcmemInd_gnNextHeader_raw_.fieldlength + LibItsRtcmem__TestSystem::RtcmemInd_gnHeaderType_raw_.fieldlength + - LibItsRtcmem__TestSystem::RtcmemInd_gnHeaderSubtype_raw_.fieldlength + LibItsRtcmem__TestSystem::RtcmemInd_gnLifetime_raw_.fieldlength + - LibItsRtcmem__TestSystem::RtcmemInd_gnTrafficClass_raw_.fieldlength + LibItsRtcmem__TestSystem::RtcmemInd_btpDestinationPort_raw_.fieldlength + - LibItsRtcmem__TestSystem::RtcmemInd_btpInfo_raw_.fieldlength + LibItsRtcmem__TestSystem::RtcmemInd_ssp_raw_.fieldlength + - LibItsRtcmem__TestSystem::RtcmemInd_its__aid_raw_.fieldlength) / + int s = (LibItsRtcmem__TypesAndValues::RtcmemInd_gnNextHeader_raw_.fieldlength + LibItsRtcmem__TypesAndValues::RtcmemInd_gnHeaderType_raw_.fieldlength + + LibItsRtcmem__TypesAndValues::RtcmemInd_gnHeaderSubtype_raw_.fieldlength + LibItsRtcmem__TypesAndValues::RtcmemInd_gnLifetime_raw_.fieldlength + + LibItsRtcmem__TypesAndValues::RtcmemInd_gnTrafficClass_raw_.fieldlength + LibItsRtcmem__TypesAndValues::RtcmemInd_btpDestinationPort_raw_.fieldlength + + LibItsRtcmem__TypesAndValues::RtcmemInd_btpInfo_raw_.fieldlength + LibItsRtcmem__TypesAndValues::RtcmemInd_ssp_raw_.fieldlength + + LibItsRtcmem__TypesAndValues::RtcmemInd_its__aid_raw_.fieldlength) / 8; // Decode CA message if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), rtcmem) == -1) { @@ -70,91 +70,91 @@ namespace LibItsRtcmem__EncdecDeclarations { TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_gnNextHeader_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_gnNextHeader_raw_.fieldlength / 8)) { p_rtcmemInd.gnNextHeader().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsRtcmem__TestSystem::RtcmemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.gnNextHeader() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__RTCMEM: gnNextHeader=", p_rtcmemInd.gnNextHeader()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_gnHeaderType_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_gnHeaderType_raw_.fieldlength / 8)) { p_rtcmemInd.gnHeaderType().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsRtcmem__TestSystem::RtcmemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.gnHeaderType() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__RTCMEM: gnHeaderType=", p_rtcmemInd.gnHeaderType()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { p_rtcmemInd.gnHeaderSubtype().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsRtcmem__TestSystem::RtcmemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.gnHeaderSubtype() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__RTCMEM: gnHeaderSubtype=", p_rtcmemInd.gnHeaderSubtype()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_gnLifetime_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_gnLifetime_raw_.fieldlength / 8)) { p_rtcmemInd.gnLifetime().set_to_omit(); } else { INTEGER i; - i.decode(LibItsRtcmem__TestSystem::RtcmemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.gnLifetime() = i; } loggers::get_instance().log_msg("fx__dec__RTCMEM: gnLifetime=", p_rtcmemInd.gnLifetime()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_gnTrafficClass_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_gnTrafficClass_raw_.fieldlength / 8)) { p_rtcmemInd.gnTrafficClass().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsRtcmem__TestSystem::RtcmemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.gnTrafficClass() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__RTCMEM: gnTrafficClass=", p_rtcmemInd.gnTrafficClass()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_btpDestinationPort_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_btpDestinationPort_raw_.fieldlength / 8)) { p_rtcmemInd.btpDestinationPort().set_to_omit(); } else { INTEGER i; - i.decode(LibItsRtcmem__TestSystem::RtcmemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.btpDestinationPort() = i; } loggers::get_instance().log_msg("fx__dec__RTCMEM: btpDestinationPort=", p_rtcmemInd.btpDestinationPort()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_btpInfo_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_btpInfo_raw_.fieldlength / 8)) { p_rtcmemInd.btpInfo().set_to_omit(); } else { INTEGER i; - i.decode(LibItsRtcmem__TestSystem::RtcmemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.btpInfo() = i; } loggers::get_instance().log_msg("fx__dec__RTCMEM: btpInfo=", p_rtcmemInd.btpInfo()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_ssp_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_ssp_raw_.fieldlength / 8)) { p_rtcmemInd.ssp().set_to_omit(); } else { BITSTRING bs; - bs.decode(LibItsRtcmem__TestSystem::RtcmemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + bs.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.ssp() = bs; } loggers::get_instance().log_msg("fx__dec__RTCMEM: ssp=", p_rtcmemInd.ssp()); loggers::get_instance().log_to_hexa("fx__dec__RTCMEM: ", decoding_buffer); // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TestSystem::RtcmemInd_its__aid_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsRtcmem__TypesAndValues::RtcmemInd_its__aid_raw_.fieldlength / 8)) { p_rtcmemInd.its__aid().set_to_omit(); } else { INTEGER i; - i.decode(LibItsRtcmem__TestSystem::RtcmemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsRtcmem__TypesAndValues::RtcmemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_rtcmemInd.its__aid() = i; } loggers::get_instance().log_msg("fx__dec__RTCMEM: its_aid=", p_rtcmemInd.its__aid()); diff --git a/ccsrc/EncDec/LibItsSecurity_Encdec.cc b/ccsrc/EncDec/LibItsSecurity_Encdec.cc index ac6219d1d2d07b3ff3c566d1a07c75fd88621e5b..703153d60f7882177203fb725caed5c9aa7939ac 100644 --- a/ccsrc/EncDec/LibItsSecurity_Encdec.cc +++ b/ccsrc/EncDec/LibItsSecurity_Encdec.cc @@ -1,138 +1,138 @@ -#include "LibItsSecurity_EncdecDeclarations.hh" - -#include "etsi_ts103097_certificate_codec.hh" -#include "etsi_ts103097_data_codec.hh" -#include "etsi_ts103097_tobesigned_certificate_codec.hh" -#include "etsi_ts103097_tobesigned_data_codec.hh" - -#include "loggers.hh" - -namespace LibItsSecurity__EncdecDeclarations { - - BITSTRING fx__enc__CertificateBase(Ieee1609Dot2::CertificateBase const &p_cert) { - loggers::get_instance().log_msg(">>> fx__enc__CertificateBase: ", p_cert); - - etsi_ts103097_certificate_codec codec; - OCTETSTRING os; - if (codec.encode(p_cert, os) == -1) { - loggers::get_instance().warning("fx__enc__CertificateBase: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__CertificateBase(BITSTRING &b, Ieee1609Dot2::CertificateBase &p_cert) { - loggers::get_instance().log_msg(">>> fx__dec__CertificateBase: ", b); - - etsi_ts103097_certificate_codec codec; - OCTETSTRING is = bit2oct(b); - if (codec.decode(is, p_cert) == -1) { - loggers::get_instance().warning("fx__dec__CertificateBase: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__CertificateBase: ", p_cert); - return 0; - } - - BITSTRING fx__enc__ToBeSignedCertificate(const Ieee1609Dot2::ToBeSignedCertificate &p_toBeSignedCertificate) { - loggers::get_instance().log_msg(">>> fx__enc__ToBeSignedCertificate: ", p_toBeSignedCertificate); - - etsi_ts103097_tobesigned_certificate_codec codec; - OCTETSTRING os; - if (codec.encode(p_toBeSignedCertificate, os) == -1) { - loggers::get_instance().warning("fx__enc__ToBeSignedCertificate: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - BITSTRING fx__enc__Ieee1609Dot2Data(const Ieee1609Dot2::Ieee1609Dot2Data &p__ieee1609Dot2Data) { - loggers::get_instance().log_msg(">>> fx__enc__Ieee1609Dot2Data: ", p__ieee1609Dot2Data); - - etsi_ts103097_data_codec codec; - OCTETSTRING os; - if (codec.encode(p__ieee1609Dot2Data, os) == -1) { - loggers::get_instance().warning("fx__enc__Ieee1609Dot2Data: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__Ieee1609Dot2Data(BITSTRING &p__data, Ieee1609Dot2::Ieee1609Dot2Data &p__ieee1609Dot2Data) { - loggers::get_instance().log_msg(">>> fx__dec__Ieee1609Dot2Data: ", p__data); - - etsi_ts103097_data_codec codec; - OCTETSTRING is = bit2oct(p__data); - if (codec.decode(is, p__ieee1609Dot2Data) == -1) { - loggers::get_instance().warning("fx__dec__Ieee1609Dot2Data: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__Ieee1609Dot2Data: ", p__ieee1609Dot2Data); - return 0; - } - - BITSTRING fx__enc__Ieee1609Dot2ToBeSignedData(const Ieee1609Dot2::ToBeSignedData &p__toBeSignedData) { - loggers::get_instance().log_msg(">>> fx__enc__Ieee1609Dot2ToBeSignedData: ", p__toBeSignedData); - - etsi_ts103097_tobesigned_data_codec codec; - OCTETSTRING os; - if (codec.encode(p__toBeSignedData, os) == -1) { - loggers::get_instance().warning("fx__enc__Ieee1609Dot2ToBeSignedData: -1 result code was returned"); - return int2bit(0, 1); - } - - return oct2bit(os); - } - - INTEGER fx__dec__Ieee1609Dot2ToBeSignedData(BITSTRING &p__data, Ieee1609Dot2::ToBeSignedData &p__toBeSignedData) { - loggers::get_instance().log_msg(">>> fx__dec__Ieee1609Dot2ToBeSignedData: ", p__data); - - etsi_ts103097_tobesigned_data_codec codec; - OCTETSTRING is = bit2oct(p__data); - if (codec.decode(is, p__toBeSignedData) == -1) { - loggers::get_instance().warning("fx__dec__Ieee1609Dot2ToBeSignedData: -1 result code was returned"); - return -1; - } - - loggers::get_instance().log_msg("<<< fx__dec__Ieee1609Dot2ToBeSignedData: ", p__toBeSignedData); - return 0; - } - - BITSTRING fx__enc__SspCAM(const LibItsSecurity__TypesAndValues::SspCAM &p__ssp) { - loggers::get_instance().log_msg(">>> fx__enc__SspCAM: ", p__ssp); - - TTCN_Buffer encoding_buffer; - p__ssp.encode(*p__ssp.get_descriptor(), encoding_buffer, TTCN_EncDec::CT_RAW); - return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); - } - - INTEGER fx__dec__SspCAM(BITSTRING &p__data, LibItsSecurity__TypesAndValues::SspCAM &p__ssp) { - loggers::get_instance().log_msg(">>> fx__dec__SspCAM: ", p__data); - - TTCN_Buffer decoding_buffer(bit2oct(p__data)); - p__ssp.decode(*p__ssp.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - return 0; - } - - BITSTRING fx__enc__SspDENM(const LibItsSecurity__TypesAndValues::SspDENM &p__ssp) { - loggers::get_instance().log_msg(">>> fx__enc__SspDENM: ", p__ssp); - - TTCN_Buffer encoding_buffer; - p__ssp.encode(*p__ssp.get_descriptor(), encoding_buffer, TTCN_EncDec::CT_RAW); - return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); - } - - INTEGER fx__dec__SspDENM(BITSTRING &p__data, LibItsSecurity__TypesAndValues::SspDENM &p__ssp) { - loggers::get_instance().log_msg(">>> fx__dec__SspDENM: ", p__data); - - TTCN_Buffer decoding_buffer(bit2oct(p__data)); - p__ssp.decode(*p__ssp.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - return 0; - } - -} // namespace LibItsSecurity__EncdecDeclarations +#include "LibItsSecurity_EncdecDeclarations.hh" + +#include "etsi_ts103097_certificate_codec.hh" +#include "etsi_ts103097_data_codec.hh" +#include "etsi_ts103097_tobesigned_certificate_codec.hh" +#include "etsi_ts103097_tobesigned_data_codec.hh" + +#include "loggers.hh" + +namespace LibItsSecurity__EncdecDeclarations { + + BITSTRING fx__enc__CertificateBase(Ieee1609Dot2::CertificateBase const &p_cert) { + loggers::get_instance().log_msg(">>> fx__enc__CertificateBase: ", p_cert); + + etsi_ts103097_certificate_codec codec; + OCTETSTRING os; + if (codec.encode(p_cert, os) == -1) { + loggers::get_instance().warning("fx__enc__CertificateBase: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__CertificateBase(BITSTRING &b, Ieee1609Dot2::CertificateBase &p_cert) { + loggers::get_instance().log_msg(">>> fx__dec__CertificateBase: ", b); + + etsi_ts103097_certificate_codec codec; + OCTETSTRING is = bit2oct(b); + if (codec.decode(is, p_cert) == -1) { + loggers::get_instance().warning("fx__dec__CertificateBase: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__CertificateBase: ", p_cert); + return 0; + } + + BITSTRING fx__enc__ToBeSignedCertificate(const Ieee1609Dot2::ToBeSignedCertificate &p_toBeSignedCertificate) { + loggers::get_instance().log_msg(">>> fx__enc__ToBeSignedCertificate: ", p_toBeSignedCertificate); + + etsi_ts103097_tobesigned_certificate_codec codec; + OCTETSTRING os; + if (codec.encode(p_toBeSignedCertificate, os) == -1) { + loggers::get_instance().warning("fx__enc__ToBeSignedCertificate: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + BITSTRING fx__enc__Ieee1609Dot2Data(const Ieee1609Dot2::Ieee1609Dot2Data &p__ieee1609Dot2Data) { + loggers::get_instance().log_msg(">>> fx__enc__Ieee1609Dot2Data: ", p__ieee1609Dot2Data); + + etsi_ts103097_data_codec codec; + OCTETSTRING os; + if (codec.encode(p__ieee1609Dot2Data, os) == -1) { + loggers::get_instance().warning("fx__enc__Ieee1609Dot2Data: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__Ieee1609Dot2Data(BITSTRING &p__data, Ieee1609Dot2::Ieee1609Dot2Data &p__ieee1609Dot2Data) { + loggers::get_instance().log_msg(">>> fx__dec__Ieee1609Dot2Data: ", p__data); + + etsi_ts103097_data_codec codec; + OCTETSTRING is = bit2oct(p__data); + if (codec.decode(is, p__ieee1609Dot2Data) == -1) { + loggers::get_instance().warning("fx__dec__Ieee1609Dot2Data: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__Ieee1609Dot2Data: ", p__ieee1609Dot2Data); + return 0; + } + + BITSTRING fx__enc__Ieee1609Dot2ToBeSignedData(const Ieee1609Dot2::ToBeSignedData &p__toBeSignedData) { + loggers::get_instance().log_msg(">>> fx__enc__Ieee1609Dot2ToBeSignedData: ", p__toBeSignedData); + + etsi_ts103097_tobesigned_data_codec codec; + OCTETSTRING os; + if (codec.encode(p__toBeSignedData, os) == -1) { + loggers::get_instance().warning("fx__enc__Ieee1609Dot2ToBeSignedData: -1 result code was returned"); + return int2bit(0, 1); + } + + return oct2bit(os); + } + + INTEGER fx__dec__Ieee1609Dot2ToBeSignedData(BITSTRING &p__data, Ieee1609Dot2::ToBeSignedData &p__toBeSignedData) { + loggers::get_instance().log_msg(">>> fx__dec__Ieee1609Dot2ToBeSignedData: ", p__data); + + etsi_ts103097_tobesigned_data_codec codec; + OCTETSTRING is = bit2oct(p__data); + if (codec.decode(is, p__toBeSignedData) == -1) { + loggers::get_instance().warning("fx__dec__Ieee1609Dot2ToBeSignedData: -1 result code was returned"); + return -1; + } + + loggers::get_instance().log_msg("<<< fx__dec__Ieee1609Dot2ToBeSignedData: ", p__toBeSignedData); + return 0; + } + + BITSTRING fx__enc__SspCAM(const LibItsSecurity__TypesAndValues::SspCAM &p__ssp) { + loggers::get_instance().log_msg(">>> fx__enc__SspCAM: ", p__ssp); + + TTCN_Buffer encoding_buffer; + p__ssp.encode(*p__ssp.get_descriptor(), encoding_buffer, TTCN_EncDec::CT_RAW); + return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); + } + + INTEGER fx__dec__SspCAM(BITSTRING &p__data, LibItsSecurity__TypesAndValues::SspCAM &p__ssp) { + loggers::get_instance().log_msg(">>> fx__dec__SspCAM: ", p__data); + + TTCN_Buffer decoding_buffer(bit2oct(p__data)); + p__ssp.decode(*p__ssp.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + return 0; + } + + BITSTRING fx__enc__SspDENM(const LibItsSecurity__TypesAndValues::SspDENM &p__ssp) { + loggers::get_instance().log_msg(">>> fx__enc__SspDENM: ", p__ssp); + + TTCN_Buffer encoding_buffer; + p__ssp.encode(*p__ssp.get_descriptor(), encoding_buffer, TTCN_EncDec::CT_RAW); + return oct2bit(OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data())); + } + + INTEGER fx__dec__SspDENM(BITSTRING &p__data, LibItsSecurity__TypesAndValues::SspDENM &p__ssp) { + loggers::get_instance().log_msg(">>> fx__dec__SspDENM: ", p__data); + + TTCN_Buffer decoding_buffer(bit2oct(p__data)); + p__ssp.decode(*p__ssp.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + return 0; + } + +} // namespace LibItsSecurity__EncdecDeclarations diff --git a/ccsrc/EncDec/LibItsSremSsem_Encdec.cc b/ccsrc/EncDec/LibItsSremSsem_Encdec.cc index 545cbee96387df56ad03e01f95fac96c42e4ad47..bfec6b0156af46c7f527c3e1edf9e9116d89c6a5 100644 --- a/ccsrc/EncDec/LibItsSremSsem_Encdec.cc +++ b/ccsrc/EncDec/LibItsSremSsem_Encdec.cc @@ -13,7 +13,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__SremReq(const LibItsSremSsem__TestSystem::SremReq &p_sremReq) { + BITSTRING fx__enc__SremReq(const LibItsSremSsem__TypesAndValues::SremReq &p_sremReq) { loggers::get_instance().log_msg(">>> fx__enc__SremReq: ", p_sremReq); SremCodec codec; @@ -31,7 +31,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__SremReq(BITSTRING &b, LibItsSremSsem__TestSystem::SremReq &p) { + INTEGER fx__dec__SremReq(BITSTRING &b, LibItsSremSsem__TypesAndValues::SremReq &p) { loggers::get_instance().log(">>> fx__dec__SremReq"); SremCodec codec; @@ -52,7 +52,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__SremInd(const LibItsSremSsem__TestSystem::SremInd &p_sremInd) { + BITSTRING fx__enc__SremInd(const LibItsSremSsem__TypesAndValues::SremInd &p_sremInd) { loggers::get_instance().log_msg(">>> fx__enc__SremInd: ", p_sremInd); SremCodec codec; @@ -70,7 +70,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__SremInd(BITSTRING &b, LibItsSremSsem__TestSystem::SremInd &p_sremInd) { + INTEGER fx__dec__SremInd(BITSTRING &b, LibItsSremSsem__TypesAndValues::SremInd &p_sremInd) { loggers::get_instance().log(">>> fx__dec__SremInd"); SremCodec codec; @@ -78,11 +78,11 @@ namespace LibItsSremSsem__EncdecDeclarations { OCTETSTRING is = bit2oct(b); // Calculate the size of the lower layers information - int s = (LibItsSremSsem__TestSystem::SremInd_gnNextHeader_raw_.fieldlength + LibItsSremSsem__TestSystem::SremInd_gnHeaderType_raw_.fieldlength + - LibItsSremSsem__TestSystem::SremInd_gnHeaderSubtype_raw_.fieldlength + LibItsSremSsem__TestSystem::SremInd_gnLifetime_raw_.fieldlength + - LibItsSremSsem__TestSystem::SremInd_gnTrafficClass_raw_.fieldlength + LibItsSremSsem__TestSystem::SremInd_btpDestinationPort_raw_.fieldlength + - LibItsSremSsem__TestSystem::SremInd_btpInfo_raw_.fieldlength + LibItsSremSsem__TestSystem::SremInd_ssp_raw_.fieldlength + - LibItsSremSsem__TestSystem::SremInd_its__aid_raw_.fieldlength) / + int s = (LibItsSremSsem__TypesAndValues::SremInd_gnNextHeader_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_gnHeaderType_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_gnHeaderSubtype_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_gnLifetime_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_gnTrafficClass_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_btpDestinationPort_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_btpInfo_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_ssp_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_its__aid_raw_.fieldlength) / 8; // Decode CA message if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), srem) == -1) { @@ -94,91 +94,91 @@ namespace LibItsSremSsem__EncdecDeclarations { TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_gnNextHeader_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnNextHeader_raw_.fieldlength / 8)) { p_sremInd.gnNextHeader().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SremInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.gnNextHeader() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SremInd: gnNextHeader=", p_sremInd.gnNextHeader()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_gnHeaderType_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderType_raw_.fieldlength / 8)) { p_sremInd.gnHeaderType().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SremInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.gnHeaderType() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SremInd: gnHeaderType=", p_sremInd.gnHeaderType()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderSubtype_raw_.fieldlength / 8)) { p_sremInd.gnHeaderSubtype().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SremInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.gnHeaderSubtype() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SremInd: gnHeaderSubtype=", p_sremInd.gnHeaderSubtype()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_gnLifetime_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnLifetime_raw_.fieldlength / 8)) { p_sremInd.gnLifetime().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SremInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.gnLifetime() = i; } loggers::get_instance().log_msg("fx__dec__SremInd: gnLifetime=", p_sremInd.gnLifetime()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_gnTrafficClass_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnTrafficClass_raw_.fieldlength / 8)) { p_sremInd.gnTrafficClass().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SremInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.gnTrafficClass() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SremInd: gnTrafficClass=", p_sremInd.gnTrafficClass()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_btpDestinationPort_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_btpDestinationPort_raw_.fieldlength / 8)) { p_sremInd.btpDestinationPort().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SremInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.btpDestinationPort() = i; } loggers::get_instance().log_msg("fx__dec__SremInd: btpDestinationPort=", p_sremInd.btpDestinationPort()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_btpInfo_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_btpInfo_raw_.fieldlength / 8)) { p_sremInd.btpInfo().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SremInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.btpInfo() = i; } loggers::get_instance().log_msg("fx__dec__SremInd: btpInfo=", p_sremInd.btpInfo()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_ssp_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_ssp_raw_.fieldlength / 8)) { p_sremInd.ssp().set_to_omit(); } else { BITSTRING bs; - bs.decode(LibItsSremSsem__TestSystem::SremInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + bs.decode(LibItsSremSsem__TypesAndValues::SremInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.ssp() = bs; } loggers::get_instance().log_msg("fx__dec__SremInd: ssp=", p_sremInd.ssp()); loggers::get_instance().log_to_hexa("fx__dec__SremInd: ", decoding_buffer); // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SremInd_its__aid_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_its__aid_raw_.fieldlength / 8)) { p_sremInd.its__aid().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SremInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_sremInd.its__aid() = i; } loggers::get_instance().log_msg("fx__dec__SremInd: its_aid=", p_sremInd.its__aid()); @@ -214,7 +214,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__SsemReq(const LibItsSremSsem__TestSystem::SsemReq &p_ssemReq) { + BITSTRING fx__enc__SsemReq(const LibItsSremSsem__TypesAndValues::SsemReq &p_ssemReq) { loggers::get_instance().log_msg(">>> fx__enc__SsemReq: ", p_ssemReq); SsemCodec codec; @@ -232,7 +232,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__SsemReq(BITSTRING &b, LibItsSremSsem__TestSystem::SsemReq &p) { + INTEGER fx__dec__SsemReq(BITSTRING &b, LibItsSremSsem__TypesAndValues::SsemReq &p) { loggers::get_instance().log(">>> fx__dec__SsemReq"); SsemCodec codec; @@ -253,7 +253,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - BITSTRING fx__enc__SsemInd(const LibItsSremSsem__TestSystem::SsemInd &p_ssemInd) { + BITSTRING fx__enc__SsemInd(const LibItsSremSsem__TypesAndValues::SsemInd &p_ssemInd) { loggers::get_instance().log_msg(">>> fx__enc__SsemInd: ", p_ssemInd); SsemCodec codec; @@ -271,7 +271,7 @@ namespace LibItsSremSsem__EncdecDeclarations { * @param value to encode * @return encoded value ****************************************************/ - INTEGER fx__dec__SsemInd(BITSTRING &b, LibItsSremSsem__TestSystem::SsemInd &p_ssemInd) { + INTEGER fx__dec__SsemInd(BITSTRING &b, LibItsSremSsem__TypesAndValues::SsemInd &p_ssemInd) { loggers::get_instance().log(">>> fx__dec__SsemInd"); SsemCodec codec; @@ -279,11 +279,11 @@ namespace LibItsSremSsem__EncdecDeclarations { OCTETSTRING is = bit2oct(b); // Calculate the size of the lower layers information - int s = (LibItsSremSsem__TestSystem::SsemInd_gnNextHeader_raw_.fieldlength + LibItsSremSsem__TestSystem::SsemInd_gnHeaderType_raw_.fieldlength + - LibItsSremSsem__TestSystem::SsemInd_gnHeaderSubtype_raw_.fieldlength + LibItsSremSsem__TestSystem::SsemInd_gnLifetime_raw_.fieldlength + - LibItsSremSsem__TestSystem::SsemInd_gnTrafficClass_raw_.fieldlength + LibItsSremSsem__TestSystem::SsemInd_btpDestinationPort_raw_.fieldlength + - LibItsSremSsem__TestSystem::SsemInd_btpInfo_raw_.fieldlength + LibItsSremSsem__TestSystem::SsemInd_ssp_raw_.fieldlength + - LibItsSremSsem__TestSystem::SsemInd_its__aid_raw_.fieldlength) / + int s = (LibItsSremSsem__TypesAndValues::SremInd_gnNextHeader_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_gnHeaderType_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_gnHeaderSubtype_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_gnLifetime_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_gnTrafficClass_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_btpDestinationPort_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_btpInfo_raw_.fieldlength + LibItsSremSsem__TypesAndValues::SremInd_ssp_raw_.fieldlength + + LibItsSremSsem__TypesAndValues::SremInd_its__aid_raw_.fieldlength) / 8; // Decode CA message if (codec.decode(OCTETSTRING(is.lengthof() - s, static_cast(is)), ssem) == -1) { @@ -295,91 +295,91 @@ namespace LibItsSremSsem__EncdecDeclarations { TTCN_Buffer decoding_buffer(OCTETSTRING(s, static_cast(is) + is.lengthof() - s)); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // gnNextHeader - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_gnNextHeader_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnNextHeader_raw_.fieldlength / 8)) { p_ssemInd.gnNextHeader().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SsemInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnNextHeader_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.gnNextHeader() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SsemInd: gnNextHeader=", p_ssemInd.gnNextHeader()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // gnHeaderType - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_gnHeaderType_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderType_raw_.fieldlength / 8)) { p_ssemInd.gnHeaderType().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SsemInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderType_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.gnHeaderType() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SsemInd: gnHeaderType=", p_ssemInd.gnHeaderType()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // gnHeaderSubtype - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_gnHeaderSubtype_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderSubtype_raw_.fieldlength / 8)) { p_ssemInd.gnHeaderSubtype().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SsemInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnHeaderSubtype_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.gnHeaderSubtype() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SsemInd: gnHeaderSubtype=", p_ssemInd.gnHeaderSubtype()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // gnLifetime - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_gnLifetime_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnLifetime_raw_.fieldlength / 8)) { p_ssemInd.gnLifetime().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SsemInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_gnLifetime_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.gnLifetime() = i; } loggers::get_instance().log_msg("fx__dec__SsemInd: gnLifetime=", p_ssemInd.gnLifetime()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // gnTrafficClass - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_gnTrafficClass_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_gnTrafficClass_raw_.fieldlength / 8)) { p_ssemInd.gnTrafficClass().set_to_omit(); } else { OCTETSTRING os; - os.decode(LibItsSremSsem__TestSystem::SsemInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + os.decode(LibItsSremSsem__TypesAndValues::SremInd_gnTrafficClass_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.gnTrafficClass() = oct2int(os); } loggers::get_instance().log_msg("fx__dec__SsemInd: gnTrafficClass=", p_ssemInd.gnTrafficClass()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // btpDestinationPort - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_btpDestinationPort_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_btpDestinationPort_raw_.fieldlength / 8)) { p_ssemInd.btpDestinationPort().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SsemInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_btpDestinationPort_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.btpDestinationPort() = i; } loggers::get_instance().log_msg("fx__dec__SsemInd: btpDestinationPort=", p_ssemInd.btpDestinationPort()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // btpInfo - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_btpInfo_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_btpInfo_raw_.fieldlength / 8)) { p_ssemInd.btpInfo().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SsemInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_btpInfo_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.btpInfo() = i; } loggers::get_instance().log_msg("fx__dec__SsemInd: btpInfo=", p_ssemInd.btpInfo()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // ssp - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_ssp_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_ssp_raw_.fieldlength / 8)) { p_ssemInd.ssp().set_to_omit(); } else { BITSTRING bs; - bs.decode(LibItsSremSsem__TestSystem::SsemInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + bs.decode(LibItsSremSsem__TypesAndValues::SremInd_ssp_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.ssp() = bs; } loggers::get_instance().log_msg("fx__dec__SsemInd: ssp=", p_ssemInd.ssp()); loggers::get_instance().log_to_hexa("fx__dec__SsemInd: ", decoding_buffer); // its__aid - if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TestSystem::SsemInd_its__aid_raw_.fieldlength / 8)) { + if (decoding_buffer.get_read_len() < static_cast(LibItsSremSsem__TypesAndValues::SremInd_its__aid_raw_.fieldlength / 8)) { p_ssemInd.its__aid().set_to_omit(); } else { INTEGER i; - i.decode(LibItsSremSsem__TestSystem::SsemInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); + i.decode(LibItsSremSsem__TypesAndValues::SremInd_its__aid_descr_, decoding_buffer, TTCN_EncDec::CT_RAW); p_ssemInd.its__aid() = i; } loggers::get_instance().log_msg("fx__dec__SsemInd: its_aid=", p_ssemInd.its__aid()); diff --git a/ccsrc/EncDec/module.mk b/ccsrc/EncDec/module.mk index 8396a33003f77754d461aeffe2ada1e6b74b782a..fd140ffe7f45b2f19aaf4615b733346de15f7b67 100644 --- a/ccsrc/EncDec/module.mk +++ b/ccsrc/EncDec/module.mk @@ -40,10 +40,10 @@ sources += \ endif ifeq (AtsIS, $(ATS)) -sources += LibItsIvim_Encdec.cc LibItsBtp_Encdec.cc \ - LibItsSremSsem_Encdec.cc LibItsBtp_Encdec.cc \ - LibItsMapemSpatem_Encdec.cc LibItsBtp_Encdec.cc \ - LibItsRtcmem_Encdec.cc LibItsBtp_Encdec.cc +sources += LibItsIvim_Encdec.cc \ + LibItsSremSsem_Encdec.cc \ + LibItsMapemSpatem_Encdec.cc \ + LibItsRtcmem_Encdec.cc endif ifeq (AtsPki, $(ATS)) diff --git a/ccsrc/Externals/AtsRSUsSimulator_externals.cc b/ccsrc/Externals/AtsRSUsSimulator_externals.cc index 68f14513e96c5a7980c8f3666c0190d0facd5edc..67006b719259198476d41260b72f9fc00a404fde 100644 --- a/ccsrc/Externals/AtsRSUsSimulator_externals.cc +++ b/ccsrc/Externals/AtsRSUsSimulator_externals.cc @@ -1,11 +1,11 @@ -#include "ItsRSUsSimulator_Functions.hh" - -namespace ItsRSUsSimulator__Functions { - void fx__computePositionFromRotation(const INTEGER &p__refLatitude, const INTEGER &p__refLongitude, const INTEGER &p__cenLatitude, - const INTEGER &p__cenLongitude, const INTEGER &p__rotation, INTEGER &p__latitude, INTEGER &p__longitude) { - // TODO - p__latitude = p__cenLatitude; - p__longitude = p__cenLongitude; - } - -} // namespace ItsRSUsSimulator__Functions +#include "ItsRSUsSimulator_Functions.hh" + +namespace ItsRSUsSimulator__Functions { + void fx__computePositionFromRotation(const INTEGER &p__refLatitude, const INTEGER &p__refLongitude, const INTEGER &p__cenLatitude, + const INTEGER &p__cenLongitude, const INTEGER &p__rotation, INTEGER &p__latitude, INTEGER &p__longitude) { + // TODO + p__latitude = p__cenLatitude; + p__longitude = p__cenLongitude; + } + +} // namespace ItsRSUsSimulator__Functions diff --git a/ccsrc/Externals/LibItsCommon_externals.cc b/ccsrc/Externals/LibItsCommon_externals.cc index 114af0a2f3080f11380086ba3a1ad35729e8aef8..9f2297b85d207a89a48efa46a1442d7e067aa5db 100644 --- a/ccsrc/Externals/LibItsCommon_externals.cc +++ b/ccsrc/Externals/LibItsCommon_externals.cc @@ -1,131 +1,131 @@ -#include "LibItsCommon_Functions.hh" -#include - -#include "base_time.hh" -#include "loggers.hh" - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif -#define earthRadius 6378137.0L -#define rbis = ((double)(earthRadius * M_PI / 180)) - -namespace LibItsCommon__Functions { - - /** - * @desc This external function gets the current time - * @return Timestamp - current time since 01/01/2004 in milliseconds - * @see fx_getCurrentTime() return TimestampIts - */ - INTEGER fx__getCurrentTime() { - INTEGER i; - i.set_long_long_val(base_time::get_instance().get_its_current_time_ms()); - loggers::get_instance().log_msg("<<< fx__getCurrentTime: ", i); - return i; - } - /** - * @desc This external function gets the current time since 01/01/1970 in UTC format - * @return The current time since 01/01/1970 in UTC format - * @see fx_getCurrentTimeUtc() return UInt64 - */ - INTEGER fx__getCurrentTimeUtc() { - INTEGER i; - i.set_long_long_val(base_time::get_instance().get_current_time_ms()); - loggers::get_instance().log_msg("<<< fx__getCurrentTimeUtc: ", i); - return i; - } - /** - * @desc Gets the current time since 01/01/2004 - * @return TimeMark - tenths of a second in the current or next hour in units of 1/10th second from UTC time - * @see function f_getCurrentTimeMark() return TimeMark - */ - INTEGER fx__getCurrentTimeMark() { - // TODO: this is just a sceleton. fill in the function - return 0; - } - - /** - * @desc Gets the Minute of current UTC year - * @return MinuteOfTheYear - tenths of a second in the current or next hour in units of 1/10th second from UTC time - * @see function f_getMinuteOfTheYear() return MinuteOfTheYear - */ - INTEGER fx__getMinuteOfTheYear() { - // TODO: this is just a sceleton. fill in the function - return 0; - } - - /** - * @desc Gets the milliseconds point in the current UTC minute - * @return DSecond - The milliseconds point in the current UTC minute (0..60000) - * @see function f_getDSecond() return DSecond - */ - INTEGER fx__getDSecond() { - // TODO: this is just a sceleton. fill in the function - return 0; - } - - /* * @desc External function to compute distance between two points - * @param p_latitudeA Latitude of first point - * @param p_longitudeA Longitude of first point - * @param p_latitudeB Latitude of second point - * @param p_longitudeB Longitude of second point - * @return Computed distance in meters - fx_computeDistance(in Int32 p_latitudeA, in Int32 p_longitudeA, in Int32 p_latitudeB, in Int32 p_longitudeB) return float; - */ - FLOAT fx__computeDistance(const INTEGER &p__latitudeA, const INTEGER &p__longitudeA, const INTEGER &p__latitudeB, const INTEGER &p__longitudeB) { - double d_latA = ((double)p__latitudeA) / 10000000.0; - double d_latB = ((double)p__latitudeB) / 10000000.0; - - double d_lonA = ((double)p__longitudeA) / 10000000.0; - double d_lonB = ((double)p__longitudeB) / 10000000.0; - - double d_lat = (d_latB - d_latA) * (M_PI / 180.0); - double d_lon = (d_lonB - d_lonA) * (M_PI / 180.0); - - double a = sin(d_lat / 2) * sin(d_lat / 2) + cos(d_latA * M_PI / 180.0) * cos(d_latB * M_PI / 180.0) * sin(d_lon / 2) * sin(d_lon / 2); - double c = 2 * atan2(sqrt(a), sqrt(1 - a)); - - return FLOAT(earthRadius * c); - } - - /* * @desc 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 - fx_computePositionUsingDistance(in Int32 p_refLatitude,in Int32 p_refLongitude,in float p_distance,in integer p_orientation,out Int32 p_latitude,out Int32 - p_longitude); - */ - void fx__computePositionUsingDistance(const INTEGER &p__refLatitude, const INTEGER &p__refLongitude, const FLOAT &p__distance, const INTEGER &p__orientation, - INTEGER &p__latitude, INTEGER &p__longitude) { - double angularD = static_cast(p__distance) / earthRadius; - double radHeading = (double)static_cast(p__orientation) * M_PI / 180; - - // Convert to rad - double lat1 = ((double)static_cast(p__refLatitude) / 10000000) * M_PI / 180; - double long1 = ((double)static_cast(p__refLongitude) / 10000000) * M_PI / 180; - - double lat2 = asin(sin(lat1) * cos(angularD) + cos(lat1) * sin(angularD) * cos(radHeading)); - double long2 = long1 + atan2(sin(radHeading) * sin(angularD) * cos(lat1), cos(angularD) - sin(lat1) * sin(lat2)); - - // normalise to -180...+180 - long2 = fmod((long2 + 3 * M_PI), (2 * M_PI) - M_PI); - - // convert to 1/10 of microdegrees - long rlat2 = round(lat2 * 10000000 / M_PI * 180); - long rlong2 = round(long2 * 10000000 / M_PI * 180); - - p__latitude = rlat2; // asin(sin(ref_lat)*cos(distance) + cos(ref_lat)*sin(distance)*cos(angle)) * 180.0 / M_PI; - p__longitude = - rlong2; //((double)p__refLongitude) + atan2(sin(angle)*sin(distance)*cos(ref_lat), cos(distance) - sin(ref_lat)*sin((double)p__latitude))*(180.0/M_PI); - } - - /* * @desc External function to compute radius of a given circular area - * @param p_squareMeters Square meters of an circular area - * @return Computed radius in meters - fx_computeRadiusFromCircularArea(in float p_squareMeters) return float; - */ - FLOAT fx__computeRadiusFromCircularArea(const FLOAT &p__squareMeters) { return FLOAT(sqrt(p__squareMeters / M_PI)); } - -} // namespace LibItsCommon__Functions +#include "LibItsCommon_Functions.hh" +#include + +#include "base_time.hh" +#include "loggers.hh" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#define earthRadius 6378137.0L +#define rbis = ((double)(earthRadius * M_PI / 180)) + +namespace LibItsCommon__Functions { + + /** + * @desc This external function gets the current time + * @return Timestamp - current time since 01/01/2004 in milliseconds + * @see fx_getCurrentTime() return TimestampIts + */ + INTEGER fx__getCurrentTime() { + INTEGER i; + i.set_long_long_val(base_time::get_instance().get_its_current_time_ms()); + loggers::get_instance().log_msg("<<< fx__getCurrentTime: ", i); + return i; + } + /** + * @desc This external function gets the current time since 01/01/1970 in UTC format + * @return The current time since 01/01/1970 in UTC format + * @see fx_getCurrentTimeUtc() return UInt64 + */ + INTEGER fx__getCurrentTimeUtc() { + INTEGER i; + i.set_long_long_val(base_time::get_instance().get_current_time_ms()); + loggers::get_instance().log_msg("<<< fx__getCurrentTimeUtc: ", i); + return i; + } + /** + * @desc Gets the current time since 01/01/2004 + * @return TimeMark - tenths of a second in the current or next hour in units of 1/10th second from UTC time + * @see function f_getCurrentTimeMark() return TimeMark + */ + INTEGER fx__getCurrentTimeMark() { + // TODO: this is just a sceleton. fill in the function + return 0; + } + + /** + * @desc Gets the Minute of current UTC year + * @return MinuteOfTheYear - tenths of a second in the current or next hour in units of 1/10th second from UTC time + * @see function f_getMinuteOfTheYear() return MinuteOfTheYear + */ + INTEGER fx__getMinuteOfTheYear() { + // TODO: this is just a sceleton. fill in the function + return 0; + } + + /** + * @desc Gets the milliseconds point in the current UTC minute + * @return DSecond - The milliseconds point in the current UTC minute (0..60000) + * @see function f_getDSecond() return DSecond + */ + INTEGER fx__getDSecond() { + // TODO: this is just a sceleton. fill in the function + return 0; + } + + /* * @desc External function to compute distance between two points + * @param p_latitudeA Latitude of first point + * @param p_longitudeA Longitude of first point + * @param p_latitudeB Latitude of second point + * @param p_longitudeB Longitude of second point + * @return Computed distance in meters + fx_computeDistance(in Int32 p_latitudeA, in Int32 p_longitudeA, in Int32 p_latitudeB, in Int32 p_longitudeB) return float; + */ + FLOAT fx__computeDistance(const INTEGER &p__latitudeA, const INTEGER &p__longitudeA, const INTEGER &p__latitudeB, const INTEGER &p__longitudeB) { + double d_latA = ((double)p__latitudeA) / 10000000.0; + double d_latB = ((double)p__latitudeB) / 10000000.0; + + double d_lonA = ((double)p__longitudeA) / 10000000.0; + double d_lonB = ((double)p__longitudeB) / 10000000.0; + + double d_lat = (d_latB - d_latA) * (M_PI / 180.0); + double d_lon = (d_lonB - d_lonA) * (M_PI / 180.0); + + double a = sin(d_lat / 2) * sin(d_lat / 2) + cos(d_latA * M_PI / 180.0) * cos(d_latB * M_PI / 180.0) * sin(d_lon / 2) * sin(d_lon / 2); + double c = 2 * atan2(sqrt(a), sqrt(1 - a)); + + return FLOAT(earthRadius * c); + } + + /* * @desc 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 + fx_computePositionUsingDistance(in Int32 p_refLatitude,in Int32 p_refLongitude,in float p_distance,in integer p_orientation,out Int32 p_latitude,out Int32 + p_longitude); + */ + void fx__computePositionUsingDistance(const INTEGER &p__refLatitude, const INTEGER &p__refLongitude, const FLOAT &p__distance, const INTEGER &p__orientation, + INTEGER &p__latitude, INTEGER &p__longitude) { + double angularD = static_cast(p__distance) / earthRadius; + double radHeading = (double)static_cast(p__orientation) * M_PI / 180; + + // Convert to rad + double lat1 = ((double)static_cast(p__refLatitude) / 10000000) * M_PI / 180; + double long1 = ((double)static_cast(p__refLongitude) / 10000000) * M_PI / 180; + + double lat2 = asin(sin(lat1) * cos(angularD) + cos(lat1) * sin(angularD) * cos(radHeading)); + double long2 = long1 + atan2(sin(radHeading) * sin(angularD) * cos(lat1), cos(angularD) - sin(lat1) * sin(lat2)); + + // normalise to -180...+180 + long2 = fmod((long2 + 3 * M_PI), (2 * M_PI) - M_PI); + + // convert to 1/10 of microdegrees + long rlat2 = round(lat2 * 10000000 / M_PI * 180); + long rlong2 = round(long2 * 10000000 / M_PI * 180); + + p__latitude = rlat2; // asin(sin(ref_lat)*cos(distance) + cos(ref_lat)*sin(distance)*cos(angle)) * 180.0 / M_PI; + p__longitude = + rlong2; //((double)p__refLongitude) + atan2(sin(angle)*sin(distance)*cos(ref_lat), cos(distance) - sin(ref_lat)*sin((double)p__latitude))*(180.0/M_PI); + } + + /* * @desc External function to compute radius of a given circular area + * @param p_squareMeters Square meters of an circular area + * @return Computed radius in meters + fx_computeRadiusFromCircularArea(in float p_squareMeters) return float; + */ + FLOAT fx__computeRadiusFromCircularArea(const FLOAT &p__squareMeters) { return FLOAT(sqrt(p__squareMeters / M_PI)); } + +} // namespace LibItsCommon__Functions diff --git a/ccsrc/Externals/LibItsDcc_externals.cc b/ccsrc/Externals/LibItsDcc_externals.cc index 1de47c84aa0d9116e307ffe1899426fa63b93a30..d6e6667dce83498aafcbc18a2f7c3c52f8724e84 100644 --- a/ccsrc/Externals/LibItsDcc_externals.cc +++ b/ccsrc/Externals/LibItsDcc_externals.cc @@ -1,11 +1,11 @@ -#include "LibItsDcc_Functions.hh" - -namespace LibItsDcc__Functions { - /* * @desc Returns the string representation of the float value - * @param p_float The float value - * @return The string representation of the float value - fx_float2str(float p_float) return charstring; - */ - // RGY no C++ implementation is needed, Titan supports this function natively - -} // namespace LibItsDcc__Functions +#include "LibItsDcc_Functions.hh" + +namespace LibItsDcc__Functions { + /* * @desc Returns the string representation of the float value + * @param p_float The float value + * @return The string representation of the float value + fx_float2str(float p_float) return charstring; + */ + // RGY no C++ implementation is needed, Titan supports this function natively + +} // namespace LibItsDcc__Functions diff --git a/ccsrc/Externals/LibItsGeoNetworking_externals.cc b/ccsrc/Externals/LibItsGeoNetworking_externals.cc index 37a5df3764d3b436b12834404517d2ef2451b02e..e73216007caa5e45cac2a95583b7d489c31b54ac 100644 --- a/ccsrc/Externals/LibItsGeoNetworking_externals.cc +++ b/ccsrc/Externals/LibItsGeoNetworking_externals.cc @@ -1,21 +1,21 @@ -#include "LibItsGeoNetworking_Functions.hh" - -#include "base_time.hh" -#include "loggers.hh" - -namespace LibItsGeoNetworking__Functions { - /* * @desc External function to compute timestamp based on current time - * @return Unix-Epoch-Time mod 2^32 - fx_computeGnTimestamp() return UInt32; - */ - INTEGER fx__computeGnTimestamp() { - INTEGER i; - i.set_long_long_val( - base_time::get_instance().get_its_current_time_ms() % - 4294967296); // Expresses the time in milliseconds at which the latitude and longitude of the ITS-S were acquired by the GeoAdhoc router. The time is - // encoded as: TST =TST(TAI)mod232 where TST(TAI) is the number of elapsed TAI milliseconds since 2004-01-01 00:00:00.000 UTC - loggers::get_instance().log_msg("<<< fx__computeGnTimestamp: ", i); - return i; - } - -} // namespace LibItsGeoNetworking__Functions +#include "LibItsGeoNetworking_Functions.hh" + +#include "base_time.hh" +#include "loggers.hh" + +namespace LibItsGeoNetworking__Functions { + /* * @desc External function to compute timestamp based on current time + * @return Unix-Epoch-Time mod 2^32 + fx_computeGnTimestamp() return UInt32; + */ + INTEGER fx__computeGnTimestamp() { + INTEGER i; + i.set_long_long_val( + base_time::get_instance().get_its_current_time_ms() % + 4294967296); // Expresses the time in milliseconds at which the latitude and longitude of the ITS-S were acquired by the GeoAdhoc router. The time is + // encoded as: TST =TST(TAI)mod232 where TST(TAI) is the number of elapsed TAI milliseconds since 2004-01-01 00:00:00.000 UTC + loggers::get_instance().log_msg("<<< fx__computeGnTimestamp: ", i); + return i; + } + +} // namespace LibItsGeoNetworking__Functions diff --git a/ccsrc/Externals/LibItsIpv6OverGeoNetworking_externals.cc b/ccsrc/Externals/LibItsIpv6OverGeoNetworking_externals.cc index 34038ef96ce24348461e1be2ea4f4a170f2b4510..661cb17d0f5f915137815a6432f0ee80a9a37496 100644 --- a/ccsrc/Externals/LibItsIpv6OverGeoNetworking_externals.cc +++ b/ccsrc/Externals/LibItsIpv6OverGeoNetworking_externals.cc @@ -1,52 +1,52 @@ -#include "LibItsIpv6OverGeoNetworking_Functions.hh" -#include -#include - -namespace LibItsIpv6OverGeoNetworking__Functions { - /* * @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 - *
-           * Pseudo header is defined by RFC 2460 - Clause 8.1
-           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-           *  |                                                               |
-           *  +                                                               +
-           *  |                                                               |
-           *  +                         Source Address                        +
-           *  |                                                               |
-           *  +                                                               +
-           *  |                                                               |
-           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-           *  |                                                               |
-           *  +                                                               +
-           *  |                                                               |
-           *  +                      Destination Address                      +
-           *  |                                                               |
-           *  +                                                               +
-           *  |                                                               |
-           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-           *  |                   Upper-Layer Packet Length                   |
-           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-           *  |                      zero                     |  Next Header  |
-           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
-           * 
- 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) UInt8 p_nextHdr - ) return Oct2; - */ - - OCTETSTRING fx__computeIPv6CheckSum(const OCTETSTRING_template &p__sourceAddress, const OCTETSTRING_template &p__destinationAddress, - const INTEGER_template &p__payloadLength, const OCTETSTRING_template &p__payload, const INTEGER_template &p__nextHdr) { - OCTETSTRING ret_val = int2oct(0, 1); - return ret_val; - } - -} // namespace LibItsIpv6OverGeoNetworking__Functions +#include "LibItsIpv6OverGeoNetworking_Functions.hh" +#include +#include + +namespace LibItsIpv6OverGeoNetworking__Functions { + /* * @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 + *
+           * Pseudo header is defined by RFC 2460 - Clause 8.1
+           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           *  |                                                               |
+           *  +                                                               +
+           *  |                                                               |
+           *  +                         Source Address                        +
+           *  |                                                               |
+           *  +                                                               +
+           *  |                                                               |
+           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           *  |                                                               |
+           *  +                                                               +
+           *  |                                                               |
+           *  +                      Destination Address                      +
+           *  |                                                               |
+           *  +                                                               +
+           *  |                                                               |
+           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           *  |                   Upper-Layer Packet Length                   |
+           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           *  |                      zero                     |  Next Header  |
+           *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+           * 
+ 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) UInt8 p_nextHdr + ) return Oct2; + */ + + OCTETSTRING fx__computeIPv6CheckSum(const OCTETSTRING_template &p__sourceAddress, const OCTETSTRING_template &p__destinationAddress, + const INTEGER_template &p__payloadLength, const OCTETSTRING_template &p__payload, const INTEGER_template &p__nextHdr) { + OCTETSTRING ret_val = int2oct(0, 1); + return ret_val; + } + +} // namespace LibItsIpv6OverGeoNetworking__Functions diff --git a/ccsrc/Externals/LibItsPki_externals.cc b/ccsrc/Externals/LibItsPki_externals.cc index 00c278c26c58a710a1b7898ce6a4170e192a3b13..b24435f5ca56a7fa7f39b15b6c2fffd5ba9b9b25 100644 --- a/ccsrc/Externals/LibItsPki_externals.cc +++ b/ccsrc/Externals/LibItsPki_externals.cc @@ -1,33 +1,33 @@ -/*! - * \file LibItsPki_externals.cc - * \brief Source file for PKI externl functions. - * \author ETSI STF594 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ - -#include "LibItsPki_Functions.hh" - -#include "loggers.hh" - -namespace LibItsPki__Functions { - - INTEGER fx__get__root__ca__certificate(const CHARSTRING &p__iut_certificate, const BOOLEAN &p__explicit_type, OCTETSTRING &p__certificate) { - loggers::get_instance().log_msg(">>> fx__get__root__ca__certificate: ", p__iut_certificate); - - CHARSTRING c("800300810038811b45545349205465737420524341204320636572746966696361746500000000001e19cf808466a8c001028002026e810201018002027081030201380102a08" - "0010f80012482080301fffc03ff0003800125820a0401ffffff04ff00000080018982060201e002ff1f80018a82060201c002ff3f80018b820e0601000000fff806ff00000000" - "0780018c820a0401ffffe004ff00001f8002027d8204010101ff00018d0001600001610001620001630001640001650001660102c0208001018002026f82060201fe02ff01c08" - "08083ee2cb68fe4618d3aff28e38b8ebdd1875221ee686c36434cc5c3d7829402d4df80805204e6e5a7fd85f9f2044a5e57646a89d0ab73e1413dda9615456fa1ea1ddf9d4834" - "51a36b7116bbc4f8fe9b4bb54478d4195c95b083ab80d77098a86f17e088"); // CERT_IUT_A_RCA - // CHARSTRING - // c("800300810079811b45545349205465737420524341204320636572746966696361746500000000001e19cf808466a88101011a0645a1042d654819f89082043b1a67c001028002026e810201018002027081030201380101a080010980012482080301fffc03ff0003800125820a0401ffffff04ff00000080018982060201e002ff1f80018a82060201c002ff3f80018b820e0601000000fff806ff000000000780018c820a0401ffffe004ff00001f8002027d8204010101ff00018d8002026f82060201fe02ff010102c0008082cab9d2e83ba971bcc5c7295ffcc4b98ca415745cf03c230d6b79a7afafeadfa38080828b5146c0160df69389e5b26e4a8a25e1ff0141c577cc24eb1626184995513f3f808068c5ab4b07fa9eef841e1d6471a310eb35333520273a6ca1cca4126b32a128d5ef56aed4439046ca0263e28c5bdd459a382837c3c97af9fd150640c44910fdbc"); - // // CERT_IUT_C_RCA - p__certificate = str2oct(c); - return 0; - } - -} // End of namespace LibItsPki__Functions +/*! + * \file LibItsPki_externals.cc + * \brief Source file for PKI externl functions. + * \author ETSI STF594 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ + +#include "LibItsPki_Functions.hh" + +#include "loggers.hh" + +namespace LibItsPki__Functions { + + INTEGER fx__get__root__ca__certificate(const CHARSTRING &p__iut_certificate, const BOOLEAN &p__explicit_type, OCTETSTRING &p__certificate) { + loggers::get_instance().log_msg(">>> fx__get__root__ca__certificate: ", p__iut_certificate); + + CHARSTRING c("800300810038811b45545349205465737420524341204320636572746966696361746500000000001e19cf808466a8c001028002026e810201018002027081030201380102a08" + "0010f80012482080301fffc03ff0003800125820a0401ffffff04ff00000080018982060201e002ff1f80018a82060201c002ff3f80018b820e0601000000fff806ff00000000" + "0780018c820a0401ffffe004ff00001f8002027d8204010101ff00018d0001600001610001620001630001640001650001660102c0208001018002026f82060201fe02ff01c08" + "08083ee2cb68fe4618d3aff28e38b8ebdd1875221ee686c36434cc5c3d7829402d4df80805204e6e5a7fd85f9f2044a5e57646a89d0ab73e1413dda9615456fa1ea1ddf9d4834" + "51a36b7116bbc4f8fe9b4bb54478d4195c95b083ab80d77098a86f17e088"); // CERT_IUT_A_RCA + // CHARSTRING + // c("800300810079811b45545349205465737420524341204320636572746966696361746500000000001e19cf808466a88101011a0645a1042d654819f89082043b1a67c001028002026e810201018002027081030201380101a080010980012482080301fffc03ff0003800125820a0401ffffff04ff00000080018982060201e002ff1f80018a82060201c002ff3f80018b820e0601000000fff806ff000000000780018c820a0401ffffe004ff00001f8002027d8204010101ff00018d8002026f82060201fe02ff010102c0008082cab9d2e83ba971bcc5c7295ffcc4b98ca415745cf03c230d6b79a7afafeadfa38080828b5146c0160df69389e5b26e4a8a25e1ff0141c577cc24eb1626184995513f3f808068c5ab4b07fa9eef841e1d6471a310eb35333520273a6ca1cca4126b32a128d5ef56aed4439046ca0263e28c5bdd459a382837c3c97af9fd150640c44910fdbc"); + // // CERT_IUT_C_RCA + p__certificate = str2oct(c); + return 0; + } + +} // End of namespace LibItsPki__Functions diff --git a/ccsrc/Externals/LibItsSecurity_externals.cc b/ccsrc/Externals/LibItsSecurity_externals.cc index 369970868c4abb65c6c13e571f3cc95b1e70b0bc..c00baec76ae262698e6657cd2dc7c98ecb8870a2 100644 --- a/ccsrc/Externals/LibItsSecurity_externals.cc +++ b/ccsrc/Externals/LibItsSecurity_externals.cc @@ -1,1523 +1,1523 @@ -/*! - * \file LibItsSecurity_externals.cc - * \brief Source file for Security externl functions. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include - -#include "LibItsCommon_Functions.hh" -#include "LibItsSecurity_Functions.hh" - -#include "hmac.hh" -#include "sha256.hh" -#include "sha384.hh" - -#include "security_ecc.hh" - -#include "security_services.hh" - -#include "geospacial.hh" - -#include -#include - -#include "loggers.hh" - -namespace LibItsSecurity__Functions { - - static std::unique_ptr g(new geospacial); - - // FIXME Unify code with security_services - - /** - * \fn OCTETSTRING fx_hashWithSha256(const OCTETSTRING& p__toBeHashedData); - * \brief Produces a 256-bit (32-bytes) hash value - * \param[in] p__toBeHashedData The data to be used to calculate the hash value - * \return The hash value - */ - OCTETSTRING fx__hashWithSha256(const OCTETSTRING &p__toBeHashedData) { - loggers::get_instance().log_msg(">>> fx__hashWithSha256: p__toBeHashedData= ", p__toBeHashedData); - - sha256 hash; - OCTETSTRING hashData; - hash.generate(p__toBeHashedData, hashData); - loggers::get_instance().log_msg("fx__hashWithSha256: hashData= ", hashData); - return hashData; - } // End of function fx__hashWithSha256 - - /** - * \fn OCTETSTRING fx_hashWithSha384(const OCTETSTRING& p__toBeHashedData); - * \brief Produces a 384-bit (48-bytes) hash value - * \param[in] p__toBeHashedData Data to be used to calculate the hash value - * \return The hash value - */ - OCTETSTRING fx__hashWithSha384(const OCTETSTRING &p__toBeHashedData) { - sha384 hash; - OCTETSTRING hashData; - hash.generate(p__toBeHashedData, hashData); - loggers::get_instance().log_msg("fx__hashWithSha384: hashData= ", hashData); - return hashData; - } // End of function fx__hashWithSha384 - - /** - * \fn OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); - * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2 - * \param[in] p__toBeSignedSecuredMessage The data to be signed - * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate - * \param[in] p__privateKey The private key - * \return The signature value - */ - OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__privateKey) { - loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: data=", p__toBeSignedSecuredMessage); - loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: issuer=", p__certificateIssuer); - loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: private key=", p__privateKey); - - // Sanity checks - if ((p__certificateIssuer.lengthof() != 32) || (p__privateKey.lengthof() != 32)) { - loggers::get_instance().log("fx__signWithEcdsaNistp256WithSha256: Wrong parameters"); - return OCTETSTRING(0, nullptr); - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeSignedSecuredMessage, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha256_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Data input) || Hash (Signer identifier input)=", hashData1); - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Calculate the signature - security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashData, r_sig, s_sig) == 0) { - OCTETSTRING os = r_sig + s_sig; - loggers::get_instance().log_msg("r_sig= ", r_sig); - loggers::get_instance().log_msg("s_sig= ", s_sig); - loggers::get_instance().log_msg("sig= ", os); - return os; - } - - return OCTETSTRING(0, nullptr); - } - - /** - * \fn OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); - * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on raw data - * \param[in] p__toBeSignedSecuredMessage The data to be signed - * \param[in] p__privateKey The private key - * \return The signature value - */ - OCTETSTRING fx__test__signWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__privateKey) { - loggers::get_instance().log_msg(">>> fx__test__signWithEcdsaNistp256WithSha256: data=", p__toBeSignedSecuredMessage); - loggers::get_instance().log_msg(">>> fx__test__signWithEcdsaNistp256WithSha256: private key=", p__privateKey); - - // Sanity checks - if (p__privateKey.lengthof() != 32) { - loggers::get_instance().log("fx__test__signWithEcdsaNistp256WithSha256: Wrong parameters"); - return OCTETSTRING(0, nullptr); - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeSignedSecuredMessage, hashData1); - loggers::get_instance().log_msg("fx__test__signWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); - // Calculate the signature - security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashData1, r_sig, s_sig) == 0) { - OCTETSTRING os = r_sig + s_sig; - loggers::get_instance().log_msg("r_sig= ", r_sig); - loggers::get_instance().log_msg("s_sig= ", s_sig); - loggers::get_instance().log_msg("sig= ", os); - return os; - } - - return OCTETSTRING(0, nullptr); - } - - /** - * \fn OCTETSTRING fx__signWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); - * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2 - * \param[in] p__toBeSignedSecuredMessage The data to be signed - * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate - * \param[in] p__privateKey The private key - * \return The signature value - */ - OCTETSTRING fx__signWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__privateKey) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 32) || (p__privateKey.lengthof() != 32)) { - loggers::get_instance().log("fx__signWithEcdsaBrainpoolp256r1WithSha256: Wrong parameters"); - return OCTETSTRING(0, nullptr); - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeSignedSecuredMessage, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha256_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256r1WithSha256: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256r1WithSha256: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256r1WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Calculate the signature - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__privateKey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashData, r_sig, s_sig) == 0) { - OCTETSTRING os = r_sig + s_sig; - loggers::get_instance().log_msg("r_sig= ", r_sig); - loggers::get_instance().log_msg("s_sig= ", s_sig); - loggers::get_instance().log_msg("sig= ", os); - return os; - } - - return OCTETSTRING(0, nullptr); - } - - /** - * \fn OCTETSTRING fx__signWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); - * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2 - * \param[in] p__toBeSignedSecuredMessage The data to be signed - * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate - * \param[in] p__privateKey The private key - * \return The signature value - */ - OCTETSTRING fx__signWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__privateKey) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 48) || (p__privateKey.lengthof() != 48)) { - loggers::get_instance().log("fx__signWithEcdsaBrainpoolp384r1WithSha384: Wrong parameters"); - return OCTETSTRING(0, nullptr); - } - - // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha384 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeSignedSecuredMessage, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 48)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha384_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Calculate the signature - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__privateKey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashData, r_sig, s_sig) == 0) { - OCTETSTRING os = r_sig + s_sig; - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: r_sig= ", r_sig); - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: s_sig= ", s_sig); - loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: sig= ", os); - return os; - } - - return OCTETSTRING(0, nullptr); - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& - * p__ecdsaNistp256PublicKeyCompressed); \brief Verify the signature of the specified data based on standard IEEE 1609.2 \param[in] p__toBeVerifiedData The - * data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate \param[in] - * p__signature The signature \param[in] p__ecdsaNistp256PublicKeyCompressed The compressed public key (x coordinate only) \return true on success, false - * otherwise - */ - BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaNistp256PublicKeyCompressed, - const INTEGER &p__compressedMode) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyCompressed.lengthof() != 32)) { - loggers::get_instance().log("fx__verifyWithEcdsaNistp256WithSha256: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha256_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Check the signature - security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyCompressed, - (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - if (k.sign_verif(hashData, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__ecdsaNistp256PublicKeyCompressed); - * \brief Verify the signature of the specified data based on raw data - * \param[in] p__toBeVerifiedData The data to be verified - * \param[in] p__signature The signature - * \param[in] p__ecdsaNistp256PublicKeyCompressed The compressed public key (x coordinate only) - * \return true on success, false otherwise - */ - BOOLEAN fx__test__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__signature, - const OCTETSTRING &p__ecdsaNistp256PublicKeyCompressed, const INTEGER &p__compressedMode) { - // Sanity checks - if ((p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyCompressed.lengthof() != 32)) { - loggers::get_instance().log("fx__test__verifyWithEcdsaNistp256WithSha256: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - loggers::get_instance().log_msg("fx__test__verifyWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); - // Check the signature - security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyCompressed, - (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - if (k.sign_verif(hashData1, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& - * p__ecdsaNistp256PublicKeyX, const OCTETSTRING& p__ecdsaNistp256PublicKeyY); \brief Verify the signature of the specified data based on standard IEEE 1609.2 - * \param[in] p__toBeVerifiedData The data to be verified - * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate - * \param[in] p__signature The signature - * \param[in] p__ecdsaNistp256PublicKeyX The public key (x coordinate) - * \param[in] p__ecdsaNistp256PublicKeyY The public key (y coordinate) - * \return true on success, false otherwise - */ - BOOLEAN fx__verifyWithEcdsaNistp256WithSha256__1(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaNistp256PublicKeyX, - const OCTETSTRING &p__ecdsaNistp256PublicKeyY) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyX.lengthof() != 32) || - (p__ecdsaNistp256PublicKeyY.lengthof() != 32)) { - loggers::get_instance().log("fx__verifyWithEcdsaNistp256WithSha256__1: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha256_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Check the signature - security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyX, p__ecdsaNistp256PublicKeyY); - // security_ecc k(ec_elliptic_curves::nist_p_256); - if (k.sign_verif(hashData, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& - * p__ecdsaBrainpoolp256PublicKeyCompressed); \brief Verify the signature of the specified data based on standard IEEE 1609.2 \param[in] p__toBeVerifiedData - * The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate \param[in] - * p__signature The signature \param[in] p__ecdsaBrainpoolp256PublicKeyCompressed The compressed public key (x coordinate only) \return true on success, false - * otherwise - */ - BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp256PublicKeyCompressed, - const INTEGER &p__compressedMode) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaBrainpoolp256PublicKeyCompressed.lengthof() != 32)) { - loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha256_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Check the signature - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__ecdsaBrainpoolp256PublicKeyCompressed, - (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - if (k.sign_verif(hashData, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& - * p__ecdsaBrainpoolp256PublicKeyX, const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyY); \brief Verify the signature of the specified data based on standard - * IEEE 1609.2 \param[in] p__toBeVerifiedData The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in - * case of self signed certificate \param[in] p__signature The signature \param[in] p__ecdsaBrainpoolp256PublicKeyX The public key (x coordinate) \param[in] - * p__ecdsaBrainpoolp256PublicKeyY The public key (y coordinate) \return true on success, false otherwise - */ - BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp256PublicKeyX, - const OCTETSTRING &p__ecdsaBrainpoolp256PublicKeyY) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaBrainpoolp256PublicKeyX.lengthof() != 32) || - (p__ecdsaBrainpoolp256PublicKeyY.lengthof() != 32)) { - loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha256 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha256_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Check the signature - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__ecdsaBrainpoolp256PublicKeyX, p__ecdsaBrainpoolp256PublicKeyY); - if (k.sign_verif(hashData, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& - * p__ecdsaBrainpoolp384PublicKeyCompressed); \brief Verify the signature of the specified data based on standard IEEE 1609.2 \param[in] p__toBeVerifiedData - * The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate \param[in] - * p__signature The signature \param[in] p__ecdsaBrainpoolp384PublicKeyCompressed The compressed public key (x coordinate only) \return true on success, false - * otherwise - */ - BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp384PublicKeyCompressed, - const INTEGER &p__compressedMode) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 48) || (p__signature.lengthof() != 96) || (p__ecdsaBrainpoolp384PublicKeyCompressed.lengthof() != 48)) { - loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha384 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 48)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha384_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Check the signature - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__ecdsaBrainpoolp384PublicKeyCompressed, - (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); - if (k.sign_verif(hashData, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& - * p__ecdsaBrainpoolp384PublicKeyX, const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyY); \brief Verify the signature of the specified data based on standard - * IEEE 1609.2 \param[in] p__toBeVerifiedData The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in - * case of self signed certificate \param[in] p__signature The signature \param[in] p__ecdsaBrainpoolp384PublicKeyX The public key (x coordinate) \param[in] - * p__ecdsaBrainpoolp384PublicKeyY The public key (y coordinate) \return true on success, false otherwise - */ - BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384__1(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, - const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp384PublicKeyX, - const OCTETSTRING &p__ecdsaBrainpoolp384PublicKeyY) { - // Sanity checks - if ((p__certificateIssuer.lengthof() != 48) || (p__signature.lengthof() != 96) || (p__ecdsaBrainpoolp384PublicKeyX.lengthof() != 48) || - (p__ecdsaBrainpoolp384PublicKeyY.lengthof() != 48)) { - loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp384r1WithSha384__1: Wrong parameters"); - return FALSE; - } - - // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - sha384 hash; - OCTETSTRING hashData1; // Hash (Data input) - hash.generate(p__toBeVerifiedData, hashData1); - OCTETSTRING hashData2; // Hash (Signer identifier input) - if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) - hashData2 = p__certificateIssuer; - } else { - hashData2 = hash.get_sha384_empty_string(); // Hash of empty string - } - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Data input)=", hashData1); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Signer identifier input)=", hashData2); - hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) - OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - hash.generate(hashData1, hashData); - loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); - // Check the signature - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__ecdsaBrainpoolp384PublicKeyX, p__ecdsaBrainpoolp384PublicKeyY); - if (k.sign_verif(hashData, p__signature) == 0) { - return TRUE; - } - - return FALSE; - } - - /** - * \fn OCTETSTRING fx__hmac__sha256(const OCTETSTRING& p__k, const OCTETSTRING& p__m); - * \brief Generate a HMAC-SHA256 value based on the provided secret key - * \param[in] p__k The secret key used for the HMAC calculation - * \param[in] p__m The message - * \return The HMAC value resized to 16-byte - */ - OCTETSTRING fx__hmac__sha256(const OCTETSTRING &p__k, const OCTETSTRING &p__m) { - loggers::get_instance().log_msg(">>> fx__hmac__sha256: p__k=", p__k); - loggers::get_instance().log_msg(">>> fx__hmac__sha256: p__m=", p__m); - - hmac h(hash_algorithms::sha_256); // TODO Use ec_encryption_algorithm - OCTETSTRING t; - if (h.generate(p__m, p__k, t) == -1) { - loggers::get_instance().warning("fx__hmac__sha256: Failed to generate HMAC"); - return OCTETSTRING(0, nullptr); - } - - loggers::get_instance().log_msg("<<< fx__hmac__sha256: HMAC: ", t); - return t; - } - - /** - * \fn OCTETSTRING fx__encrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt); - * \brief Encrypt the message using AES 128 CCM algorithm - * \param[in] p__k The symmetric encryption key - * \param[in] p__n The initial vector, nonce vector - * \param[in] p__pt The message to encrypt - * \return The encrypted message concatenated to the AES 128 CCM tag - */ - OCTETSTRING fx__encrypt__aes__128__ccm__test(const OCTETSTRING &p__k, const OCTETSTRING &p__n, const OCTETSTRING &p__pt) { - loggers::get_instance().log(">>> fx__encrypt__aes__128__ccm__test"); - - security_ecc ec(ec_elliptic_curves::nist_p_256); - OCTETSTRING enc_message; - if (ec.encrypt(encryption_algotithm::aes_128_ccm, p__k, p__n, p__pt, enc_message) == -1) { - loggers::get_instance().warning("fx__encrypt__aes__128__ccm__test: Failed to encrypt message"); - return OCTETSTRING(0, nullptr); - } - OCTETSTRING os(enc_message + ec.tag()); - loggers::get_instance().log_msg("fx__encrypt__aes__128__ccm__test: encrypted message: ", os); - - return os; - } - - /** - * \fn OCTETSTRING fx__encrypt__aes__128__gcm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt); - * \brief Encrypt the message using AES 128 GCM algorithm - * \param[in] p__k The symmetric encryption key - * \param[in] p__n The initial vector, nonce vector - * \param[in] p__pt The message to encrypt - * \return The encrypted message concatenated to the AES 128 CCM tag - */ - OCTETSTRING fx__encrypt__aes__128__gcm__test(const OCTETSTRING &p__k, const OCTETSTRING &p__n, const OCTETSTRING &p__pt) { - loggers::get_instance().log(">>> fx__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__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__encrypt__aes__128__gcm__test: encrypted message: ", os); - - return os; - } - - /** - * \fn OCTETSTRING fx__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 - * \param[in] p__k The symmetric encryption key - * \param[in] p__n The initial vector, nonce vector - * \param[in] p__ct The encrypted message concatenated to the AES 128 CCM tag - * \return The original message - */ - OCTETSTRING fx__decrypt__aes__128__ccm__test(const OCTETSTRING &p__k, const OCTETSTRING &p__n, const OCTETSTRING &p__ct) { - loggers::get_instance().log_msg(">>> fx__decrypt__aes__128__ccm__test: p__k: ", p__k); - loggers::get_instance().log_msg(">>> fx__decrypt__aes__128__ccm__test: p__n: ", p__n); - loggers::get_instance().log_msg(">>> fx__decrypt__aes__128__ccm__test: p__ct: ", p__ct); - - security_ecc ec(ec_elliptic_curves::nist_p_256); - // Extract the tag - OCTETSTRING tag(16, p__ct.lengthof() - 16 + static_cast(p__ct)); - loggers::get_instance().log_msg("fx__decrypt__aes__128__ccm__test: tag: ", tag); - // Remove the tag from the end of the encrypted message - OCTETSTRING ct(p__ct.lengthof() - 16, static_cast(p__ct)); - loggers::get_instance().log_msg("fx__decrypt__aes__128__ccm__test: ct: ", ct); - - OCTETSTRING message; - if (ec.decrypt(encryption_algotithm::aes_128_ccm, p__k, p__n, tag, ct, message) == -1) { - loggers::get_instance().warning("fx__decrypt__aes__128__ccm__test: Failed to decrypt message"); - return OCTETSTRING(0, nullptr); - } - loggers::get_instance().log_to_hexa("fx__decrypt__aes__128__ccm__test: decrypted message: ", message); - - return message; - } - - /** - * \fn OCTETSTRING fx__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyX, const - * OCTETSTRING& p__recipientsPublicKeyY, OCTETSTRING& p__publicEphemeralKeyX, OCTETSTRING& p__publicEphemeralKeyY, OCTETSTRING& p__encrypted__sym__key, - * OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce); \brief Encrypt the message using ECIES algorithm to encrypt AES 128 CCM symmetric key, as - * defined in IEEE Std 1609.2-2017 \param[in] p__toBeEncryptedSecuredMessage The message to be encrypted \param[in] p__recipientsPublicKeyCompressed The - * Recipient's compressed public key \param[in] p__compressedMode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise \param[out] - * p__publicEphemeralKeyCompressed The public ephemeral compressed key \param[out] p__ephemeralCompressedMode The compressed mode, 0 if the latest bit of - * Y-coordinate is 0, 1 otherwise \param[out] p__encrypted__sym__key The encrypted AES 128 symmetric key \param[out] p__authentication__vector The tag of the - * encrypted AES 128 symmetric key \param[out] p__nonce The nonce vector \return The original message \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key - * encryption algorithms: ECIES \see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/ \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, const OCTETSTRING &p__salt, OCTETSTRING &p__publicEphemeralKeyCompressed, - INTEGER &p__ephemeralCompressedMode, OCTETSTRING &p__aes__sym__key, 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 Ephemeral key - std::unique_ptr ec; - ec.reset(new security_ecc(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 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(), p__salt) == -1) { - loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to generate and derive secret key"); - return OCTETSTRING(0, nullptr); - } - - // Set the AES symmetric key - loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: AES symmetric key: ", ec->symmetric_encryption_key()); - p__aes__sym__key = ec->symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__aes__sym__key: ", p__aes__sym__key); - // Set the encrypted symmetric key - loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Encrypted symmetric key: ", ec->encrypted_symmetric_key()); - p__encrypted__sym__key = ec->encrypted_symmetric_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); - 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); - // 3. Retrieve AES 128 parameters - p__nonce = ec->nonce(); - loggers::get_instance().log_msg("fx__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__encryptWithEciesNistp256WithSha256: Failed to encrypt message"); - return OCTETSTRING(0, nullptr); - } - enc_message += ec->tag(); - loggers::get_instance().log_to_hexa("fx__encryptWithEciesNistp256WithSha256: enc message||Tag: ", enc_message); - - 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__aes__sym__key, 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); - } - - // Set the AES symmetric key - loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: AES symmetric key: ", ec.symmetric_encryption_key()); - p__aes__sym__key = ec.symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: p__aes__sym__key: ", p__aes__sym__key); - // Set the encrypted symmetric key - loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: Encrypted symmetric key: ", ec.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 \param[in] p__encryptedSecuredMessage The encrypted message \param[in] p__privateEncKey The private encryption key \param[in] - * p__publicEphemeralKeyCompressed The public ephemeral compressed key \param[in] p__ephemeralCompressedMode The compressed mode, 0 if the latest bit of - * Y-coordinate is 0, 1 otherwise \param[in] p__encrypted__sym__key The encrypted AES 128 symmetric key \param[in] p__authentication__vector The tag of the - * encrypted AES 128 symmetric key \param[in] p__nonce The nonce vector \return The original message \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key - * encryption algorithms: ECIES \see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/ \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, const OCTETSTRING &p__salt, OCTETSTRING &p__aes__sym__enc__key) { - 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); - loggers::get_instance().log(">>> fx__decryptWithEciesNistp256WithSha256: p__ephemeralCompressedMode: %d", static_cast(p__ephemeralCompressedMode)); - 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 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 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); - } - - // Decrypt the message - OCTETSTRING enc_message(p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof(), - static_cast(p__encryptedSecuredMessage)); // Extract the encrypted message - loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: enc_message: ", enc_message); // Extract the ctag value - OCTETSTRING tag(ec.tag().lengthof(), - static_cast(p__encryptedSecuredMessage) + p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof()); - loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: tag: ", tag); - OCTETSTRING message; - if (ec.decrypt(tag, enc_message, message) == -1) { - loggers::get_instance().warning("fx__decryptWithEciesNistp256WithSha256: Failed to generate shared secret"); - return OCTETSTRING(0, nullptr); - } - loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: dec message: ", message); - p__aes__sym__enc__key = ec.symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: AES 128 encryption key: ", p__aes__sym__enc__key); - - return message; - } - - OCTETSTRING fx__encryptWithEciesBrainpoolp256r1WithSha256(const OCTETSTRING &p__toBeEncryptedSecuredMessage, - const OCTETSTRING &p__recipientsPublicKeyCompressed, const INTEGER &p__compressedMode, - const OCTETSTRING &p__salt, OCTETSTRING &p__publicEphemeralKeyCompressed, - INTEGER &p__ephemeralCompressedMode, OCTETSTRING &p__aes__sym__key, - OCTETSTRING &p__encrypted__sym__key, OCTETSTRING &p__authentication__vector, - OCTETSTRING &p__nonce) { - loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__toBeEncryptedSecuredMessage: ", p__toBeEncryptedSecuredMessage); - loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__recipientsPublicKeyCompressed: ", p__recipientsPublicKeyCompressed); - loggers::get_instance().log(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__compressedMode: %d", static_cast(p__compressedMode)); - loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__salt: ", p__salt); - - // 1. Generate new Private/Public Ephemeral key - std::unique_ptr ec; - ec.reset(new security_ecc(ec_elliptic_curves::brainpool_p_256_r1)); - if (ec->generate() == -1) { - loggers::get_instance().warning("fx__encryptWithEciesBrainpoolp256r1WithSha256: Failed to generate ephemeral keys"); - return OCTETSTRING(0, nullptr); - } - // 2. Generate and derive shared secret based on recipient's private keys - 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(), p__salt) == -1) { - loggers::get_instance().warning("fx__encryptWithEciesBrainpoolp256r1WithSha256: Failed to generate and derive secret key"); - return OCTETSTRING(0, nullptr); - } - - // Set the AES symmetric key - loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: AES symmetric key: ", ec->symmetric_encryption_key()); - p__aes__sym__key = ec->symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: p__aes__sym__key: ", p__aes__sym__key); - // Set the encrypted symmetric key - loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: Encrypted symmetric key: ", ec->encrypted_symmetric_key()); - p__encrypted__sym__key = ec->encrypted_symmetric_key(); - loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: p__authentication__vector: ", p__authentication__vector); - // Set ephemeral public keys - p__publicEphemeralKeyCompressed = ec->public_key_compressed(); - loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: Ephemeral public compressed key: ", p__publicEphemeralKeyCompressed); - p__ephemeralCompressedMode = (ec->public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) ? 0 : 1; - loggers::get_instance().log("fx__encryptWithEciesBrainpoolp256r1WithSha256: Ephemeral public compressed mode: %d: ", p__ephemeralCompressedMode); - // 3. Retrieve AES 128 parameters - p__nonce = ec->nonce(); - loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: Failed to encrypt message"); - return OCTETSTRING(0, nullptr); - } - enc_message += ec->tag(); - loggers::get_instance().log_to_hexa("fx__encryptWithEciesBrainpoolp256r1WithSha256: enc message||Tag: ", enc_message); - - return enc_message; - } - - /** - * @desc Test function for ECIES BRAINPOOL P-256r1 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__encryptWithEciesBrainpoolp256r1WithSha256(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__aes__sym__key, - 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::brainpool_p_256_r1, p__privateEphemeralKey); - p__publicEphemeralKeyX = ec.public_key_x(); - p__publicEphemeralKeyY = ec.public_key_y(); - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: Vx=", p__publicEphemeralKeyX); - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: Vy=", p__publicEphemeralKeyY); - - // 2. Generate and derive shared secret - security_ecc ec_comp(ec_elliptic_curves::brainpool_p_256_r1, p__recipientPublicKeyX, p__recipientPublicKeyY); - ec.symmetric_encryption_key(p__toBeEncryptedSecuredMessage); - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: ", 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__encryptWithEciesBrainpoolp256r1WithSha256: Failed to generate and derive secret key"); - return OCTETSTRING(0, nullptr); - } - - // Set the AES symmetric key - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: AES symmetric key: ", ec.symmetric_encryption_key()); - p__aes__sym__key = ec.symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: p__aes__sym__key: ", p__aes__sym__key); - // Set the encrypted symmetric key - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: Encrypted symmetric key: ", ec.encrypted_symmetric_key()); - p__encrypted__sym__key = ec.encrypted_symmetric_key(); - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: p__authentication__vector: ", p__authentication__vector); - // 3. Retrieve AES 128 parameters - p__nonce = ec.nonce(); - loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: Failed to encrypt message"); - return OCTETSTRING(0, nullptr); - } - enc_message += ec.tag(); - loggers::get_instance().log_to_hexa("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: enc message||Tag: ", enc_message); - - return enc_message; - } - - OCTETSTRING fx__decryptWithEciesBrainpoolp256r1WithSha256(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, OCTETSTRING &p__aes__sym__enc__key) { - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__toBeEncryptedSecuredMessage: ", p__encryptedSecuredMessage); - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__privateEncKey: ", p__privateEncKey); - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__publicEphemeralKeyCompressed: ", p__publicEphemeralKeyCompressed); - loggers::get_instance().log(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__ephemeralCompressedMode: %d", - static_cast(p__ephemeralCompressedMode)); - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__nonce: ", p__nonce); - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__authentication__vector: ", p__authentication__vector); - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key); - loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__salt", p__salt); - - // 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 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__decryptWithEciesBrainpoolp256r1WithSha256: Failed to generate shared secret"); - return OCTETSTRING(0, nullptr); - } - - // Decrypt the message - OCTETSTRING enc_message(p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof(), - static_cast(p__encryptedSecuredMessage)); // Extract the encrypted message - loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: enc_message: ", enc_message); // Extract the ctag value - OCTETSTRING tag(ec.tag().lengthof(), - static_cast(p__encryptedSecuredMessage) + p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof()); - loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: tag: ", tag); - OCTETSTRING message; - if (ec.decrypt(tag, enc_message, message) == -1) { - loggers::get_instance().warning("fx__decryptWithEciesBrainpoolp256r1WithSha256: Failed to generate shared secret"); - return OCTETSTRING(0, nullptr); - } - loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: dec message: ", message); - p__aes__sym__enc__key = ec.symmetric_encryption_key(); - loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: AES 128 encryption key: ", p__aes__sym__enc__key); - - return message; - } - - /** - * \brief Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm. - * This function should not be used by the ATS - * \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 - fx_generateKeyPair_nistp256(out octetstring p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean; - */ - BOOLEAN fx__generateKeyPair__nistp256(OCTETSTRING &p__privateKey, OCTETSTRING &p__publicKeyX, OCTETSTRING &p__publicKeyY, OCTETSTRING &p__publicKeyCompressed, - INTEGER &p__compressedMode) { - security_ecc k(ec_elliptic_curves::nist_p_256); - if (k.generate() != 0) { - p__privateKey = OCTETSTRING(0, nullptr); - p__publicKeyX = OCTETSTRING(0, nullptr); - p__publicKeyY = OCTETSTRING(0, nullptr); - p__publicKeyCompressed = OCTETSTRING(0, nullptr); - return FALSE; - } - // Sanity checks - if (k.private_key().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid private key size"); - return FALSE; - } - if (k.public_key_x().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public key X-coordonate size"); - return FALSE; - } - if (k.public_key_y().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public key Y-coordonate size"); - return FALSE; - } - if (k.public_key_compressed().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public compressed key size"); - return FALSE; - } - p__privateKey = k.private_key(); - p__publicKeyX = k.public_key_x(); - p__publicKeyY = k.public_key_y(); - p__publicKeyCompressed = k.public_key_compressed(); - p__compressedMode = INTEGER((int)k.public_key_compressed_mode()); - - return TRUE; - } - - /** - * \brief Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm. - * This function should not be used by the ATS - * \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 - fx_generateKeyPair_nistp256(out octetstring p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean; - */ - BOOLEAN fx__generateKeyPair__brainpoolp256r1(OCTETSTRING &p__privateKey, OCTETSTRING &p__publicKeyX, OCTETSTRING &p__publicKeyY, - OCTETSTRING &p__publicKeyCompressed, INTEGER &p__compressedMode) { - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1); - if (k.generate() != 0) { - p__privateKey = OCTETSTRING(0, nullptr); - p__publicKeyX = OCTETSTRING(0, nullptr); - p__publicKeyY = OCTETSTRING(0, nullptr); - p__publicKeyCompressed = OCTETSTRING(0, nullptr); - return FALSE; - } - - // Sanity checks - if (k.private_key().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid private key size"); - return FALSE; - } - if (k.public_key_x().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid public key X-coordonate size"); - return FALSE; - } - if (k.public_key_y().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid public key Y-coordonate size"); - return FALSE; - } - if (k.public_key_compressed().lengthof() != 32) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid public compressed key size"); - return FALSE; - } - p__privateKey = k.private_key(); - p__publicKeyX = k.public_key_x(); - p__publicKeyY = k.public_key_y(); - p__publicKeyCompressed = k.public_key_compressed(); - p__compressedMode = INTEGER((int)k.public_key_compressed_mode()); - - return TRUE; - } - - /** - * \brief Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm. - * This function should not be used by the ATS - * \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 - fx_generateKeyPair_nistp256(out octetstring p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean; - */ - BOOLEAN fx__generateKeyPair__brainpoolp384r1(OCTETSTRING &p__privateKey, OCTETSTRING &p__publicKeyX, OCTETSTRING &p__publicKeyY, - OCTETSTRING &p__publicKeyCompressed, INTEGER &p__compressedMode) { - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1); - if (k.generate() != 0) { - p__privateKey = OCTETSTRING(0, nullptr); - p__publicKeyX = OCTETSTRING(0, nullptr); - p__publicKeyY = OCTETSTRING(0, nullptr); - p__publicKeyCompressed = OCTETSTRING(0, nullptr); - return FALSE; - } - - // Sanity checks - if (k.private_key().lengthof() != 48) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid private key size"); - return FALSE; - } - if (k.public_key_x().lengthof() != 48) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid public key X-coordonate size"); - return FALSE; - } - if (k.public_key_y().lengthof() != 48) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid public key Y-coordonate size"); - return FALSE; - } - if (k.public_key_compressed().lengthof() != 48) { - loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid public compressed key size"); - return FALSE; - } - p__privateKey = k.private_key(); - p__publicKeyX = k.public_key_x(); - p__publicKeyY = k.public_key_y(); - p__publicKeyCompressed = k.public_key_compressed(); - p__compressedMode = INTEGER((int)k.public_key_compressed_mode()); - - return TRUE; - } - - BOOLEAN fx__get__uncompressed__key__nistp256(const OCTETSTRING &p__privateKey, const OCTETSTRING &p__publicKeyCompressed, const INTEGER &p__compressedMode, - OCTETSTRING &p__publicKeyY) { - security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey); - - // Sanity checks - if (k.private_key().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid private key size"); - return FALSE; - } - if (k.public_key_x().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public key X-coordonate size"); - return FALSE; - } - if (k.public_key_y().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public key Y-coordonate size"); - return FALSE; - } - if (k.public_key_compressed().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public compressed key size"); - return FALSE; - } - // if (p__compressedMode != INTEGER((int)k.public_key_compressed_mode())) { - // loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public compressed mode"); - // return FALSE; - // } - // if (p__publicKeyCompressed != k.public_key_compressed()) { - // loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public compressed key value"); - // return FALSE; - // } - - p__publicKeyY = k.public_key_y(); - - return TRUE; - } - - BOOLEAN fx__get__uncompressed__key__brainpoolp256r1(const OCTETSTRING &p__privateKey, const OCTETSTRING &p__publicKeyCompressed, - const INTEGER &p__compressedMode, OCTETSTRING &p__publicKeyY) { - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__privateKey); - - // Sanity checks - if (k.private_key().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid private key size"); - return FALSE; - } - if (k.public_key_x().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public key X-coordonate size"); - return FALSE; - } - if (k.public_key_y().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public key Y-coordonate size"); - return FALSE; - } - if (k.public_key_compressed().lengthof() != 32) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public compressed key size"); - return FALSE; - } - // if (p__compressedMode != INTEGER((int)k.public_key_compressed_mode())) { - // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public compressed mode"); - // return FALSE; - // } - // if (p__publicKeyCompressed != k.public_key_compressed()) { - // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public compressed key value"); - // return FALSE; - // } - - p__publicKeyY = k.public_key_y(); - - return TRUE; - } - - BOOLEAN fx__get__uncompressed__key__brainpoolp384r1(const OCTETSTRING &p__privateKey, const OCTETSTRING &p__publicKeyCompressed, - const INTEGER &p__compressedMode, OCTETSTRING &p__publicKeyY) { - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__privateKey); - - // Sanity checks - if (k.private_key().lengthof() != 48) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid private key size"); - return FALSE; - } - if (k.public_key_x().lengthof() != 48) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public key X-coordonate size"); - return FALSE; - } - if (k.public_key_y().lengthof() != 48) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public key Y-coordonate size"); - return FALSE; - } - if (k.public_key_compressed().lengthof() != 48) { - loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public compressed key size"); - return FALSE; - } - // if (p__compressedMode != INTEGER((int)k.public_key_compressed_mode())) { - // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public compressed mode"); - // return FALSE; - // } - // if (p__publicKeyCompressed != k.public_key_compressed()) { - // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public compressed key value"); - // return FALSE; - // } - - p__publicKeyY = k.public_key_y(); - - return TRUE; - } - - // group encryption - - // group certificatesLoader - - /** - * \brief 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 - * @remark This method SHALL be call before any usage of certificates - * \return true on success, false otherwise - fx_loadCertificates(in charstring p_rootDirectory, in charstring p_configId) return boolean; - */ - BOOLEAN fx__loadCertificates(const CHARSTRING &p__rootDirectory, const CHARSTRING &p__configId) { - loggers::get_instance().log(">>> fx__loadCertificates: '%s', '%s'", static_cast(p__rootDirectory), static_cast(p__configId)); - - std::string str(static_cast(p__rootDirectory)); - if (p__configId.lengthof() != 0) { - str += "/"; - str += std::string(static_cast(p__configId)); - } - params params; - params.insert(std::pair(std::string("sec_db_path"), str)); - if (security_services::get_instance().setup(params) == -1) { - return FALSE; - } - - return TRUE; - } - - BOOLEAN fx__store__certificate(const CHARSTRING &p__cert__id, const OCTETSTRING &p__cert, const OCTETSTRING &p__private__key, - const OCTETSTRING &p__public__key__x, const OCTETSTRING &p__public__key__y, const OCTETSTRING &p__public__key__compressed, - const INTEGER &p__public__key__compressed__mode, const OCTETSTRING &p__hash, const OCTETSTRING &p__hash__256, - const OCTETSTRING &p__hashid8, const OCTETSTRING &p__issuer, const OCTETSTRING_template &p__private__enc__key, - const OCTETSTRING_template &p__public__enc__key__x, const OCTETSTRING_template &p__public__enc__key__y, - const OCTETSTRING_template &p__public__enc__compressed__key, const INTEGER_template &p__public__enc__key__compressed__mode) { - loggers::get_instance().log(">>> fx__store__certificate: '%s'", static_cast(p__cert__id)); - - int result; - if (!p__private__enc__key.is_omit()) { - const OCTETSTRING private_enc_key = p__private__enc__key.valueof(); - const OCTETSTRING public_enc_key_x = p__public__enc__key__x.valueof(); - const OCTETSTRING public_enc_key_y = p__public__enc__key__y.valueof(); - result = security_services::get_instance().store_certificate( - p__cert__id, p__cert, p__private__key, p__public__key__x, p__public__key__y, p__public__key__compressed, p__public__key__compressed__mode, p__hash, - p__hash__256, p__hashid8, p__issuer, p__private__enc__key.valueof(), p__public__enc__key__x.valueof(), p__public__enc__key__y.valueof(), - p__public__enc__compressed__key.valueof(), p__public__enc__key__compressed__mode.valueof()); - } else { - result = security_services::get_instance().store_certificate( - p__cert__id, p__cert, p__private__key, p__public__key__x, p__public__key__y, p__public__key__compressed, p__public__key__compressed__mode, p__hash, - p__hash__256, p__hashid8, p__issuer, OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), INTEGER(-1)); - } - - return (result == 0); - } - - /** - * \brief Unload from memory cache the certificates - * \return true on success, false otherwise - */ - BOOLEAN fx__unloadCertificates() { return TRUE; } - - /** - * \brief Read the specified certificate - * \param p_certificate_id the certificate identifier - * \param p_certificate the expected certificate - * \return true on success, false otherwise - */ - BOOLEAN fx__readCertificate(const CHARSTRING &p__certificateId, OCTETSTRING &p__certificate) { - loggers::get_instance().log(">>> fx__readCertificate: '%s'", static_cast(p__certificateId)); - - if (security_services::get_instance().read_certificate(p__certificateId, p__certificate) == -1) { - return FALSE; - } - - return TRUE; - } - - BOOLEAN fx__readCertificateFromDigest(const OCTETSTRING &p__digest, CHARSTRING &p__certificateId) { - loggers::get_instance().log_msg(">>> fx__readCertificateFromDigest: ", p__digest); - - if (security_services::get_instance().read_certificate_from_digest(p__digest, p__certificateId) == -1) { - return FALSE; - } - loggers::get_instance().log_msg("fx__readCertificateFromDigest: ", p__certificateId); - - return TRUE; - } - - BOOLEAN fx__readCertificateFromHashedId3(const OCTETSTRING &p__digest, CHARSTRING &p__certificateId) { - loggers::get_instance().log_msg(">>> fx__readCertificateFromHashedId3: ", p__digest); - - if (security_services::get_instance().read_certificate_from_hashed_id3(p__digest, p__certificateId) == -1) { - return FALSE; - } - loggers::get_instance().log_msg("fx__readCertificateFromHashedId3: ", p__certificateId); - - return TRUE; - } - - /** - * \brief Read the specified certificate digest - * \param p_certificate_id the certificate identifier - * \param p_digest the expected certificate - * \return true on success, false otherwise - */ - BOOLEAN fx__readCertificateDigest(const CHARSTRING &p__certificateId, OCTETSTRING &p__digest) { - loggers::get_instance().log(">>> fx__readCertificateDigest: '%s'", static_cast(p__certificateId)); - - if (security_services::get_instance().read_certificate_digest(p__certificateId, p__digest) == -1) { - return FALSE; - } - - return TRUE; - } - - /** - * \brief Read the whole-hash of the certificate - * \param p_certificate_id the certificate identifier - * \param p_hash the expected certificate - * \return true on success, false otherwise - */ - BOOLEAN fx__readCertificateHash(const CHARSTRING &p__certificateId, OCTETSTRING &p__hash) { - loggers::get_instance().log(">>> fx__readCertificateHash: '%s'", static_cast(p__certificateId)); - - if (security_services::get_instance().read_certificate_hash(p__certificateId, p__hash) == -1) { - return FALSE; - } - - return TRUE; - } - - /** - * \brief Read the whole-hash of the certificate using SHA 256 - * \param p_certificate_id the certificate identifier - * \param p_hash the expected certificate - * \return true on success, false otherwise - */ - BOOLEAN fx__readCertificateHash256(const CHARSTRING &p__certificateId, OCTETSTRING &p__hash) { - loggers::get_instance().log(">>> fx__readCertificateHash256: '%s'", static_cast(p__certificateId)); - - if (security_services::get_instance().read_certificate_hash_sha_256(p__certificateId, p__hash) == -1) { - return FALSE; - } - - return TRUE; - } - - /** - * \brief Read the private keys for the specified certificate - * \param p_certificate_id the keys identifier - * \param p_signingPrivateKey the signing private key - * \return true on success, false otherwise - */ - BOOLEAN fx__readSigningKey(const CHARSTRING &p__certificateId, OCTETSTRING &p__signingPrivateKey) { - loggers::get_instance().log(">>> fx__readSigningKey: '%s'", static_cast(p__certificateId)); - - if (security_services::get_instance().read_private_key(p__certificateId, p__signingPrivateKey) == -1) { - return FALSE; - } - - return TRUE; - } - - /** - * \brief Read the private keys for the specified certificate - * \param p_keysId the keys identifier - * \param p_encryptPrivateKey the encrypt private key - * \return true on success, false otherwise - fx_readEncryptingKey(in charstring p_keysId, out Oct32 p_encryptingPrivateKey) return boolean; - */ - BOOLEAN fx__readEncryptingKey(const CHARSTRING &p__certificateId, OCTETSTRING &p__encryptingPrivateKey) { - loggers::get_instance().log(">>> fx__readSigningKey: '%s'", static_cast(p__certificateId)); - - if (security_services::get_instance().read_private_enc_key(p__certificateId, p__encryptingPrivateKey) == -1) { - return FALSE; - } - - return TRUE; - } - - // group geospacial - - /* * \brief Check that given polygon doesn't have neither self-intersections nor holes. - * \param p_region Polygonal Region - * \return true on success, false otherwise - * @verdict Unchanged - fx_isValidPolygonalRegion(in PolygonalRegion p_region) return boolean; - */ - BOOLEAN fx__isValidPolygonalRegion(const Ieee1609Dot2BaseTypes::PolygonalRegion &p__region) { return TRUE; } - - /* * \brief Check if a polygonal region 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 - fx_isPolygonalRegionInside(in PolygonalRegion p_parent, in PolygonalRegion p_region) return boolean; - */ - BOOLEAN fx__isPolygonalRegionInside(const Ieee1609Dot2BaseTypes::PolygonalRegion &p__parent, const Ieee1609Dot2BaseTypes::PolygonalRegion &p__region) { - return TRUE; - } - - /* * \brief 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 - fx_isLocationInsideCircularRegion(in CircularRegion p_region, in ThreeDLocation p_location) return boolean; - */ - BOOLEAN fx__isLocationInsideCircularRegion(const Ieee1609Dot2BaseTypes::CircularRegion &p__region, const Ieee1609Dot2BaseTypes::ThreeDLocation &p__location) { - return TRUE; - } - - /* * \brief 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 - fx_isLocationInsideRectangularRegion(in SequenceOfRectangularRegion p_region, in ThreeDLocation p_location) return boolean; - */ - BOOLEAN fx__isLocationInsideRectangularRegion(const Ieee1609Dot2BaseTypes::SequenceOfRectangularRegion &p__region, - const Ieee1609Dot2BaseTypes::ThreeDLocation & p__location) { - return TRUE; - } - - /* * \brief 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 - fx_isLocationInsidePolygonalRegion(in PolygonalRegion p_region, in ThreeDLocation p_location) return boolean; - */ - BOOLEAN fx__isLocationInsidePolygonalRegion(const Ieee1609Dot2BaseTypes::PolygonalRegion &p__region, - const Ieee1609Dot2BaseTypes::ThreeDLocation & p__location) { - return TRUE; - } - - /* * \brief 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 - fx_isLocationInsideIdentifiedRegion(in IdentifiedRegion p_region, in ThreeDLocation p_location) return boolean; - */ - BOOLEAN fx__isLocationInsideIdentifiedRegion(const Ieee1609Dot2BaseTypes::IdentifiedRegion &p__region, - const Ieee1609Dot2BaseTypes::ThreeDLocation & p__location) { - return TRUE; - } - - /* * \brief Check if the location is inside an undefined region - * \param p_region The identified region to consider - * \param p_location The device location - * \return true on success, false otherwise - * @verdict Unchanged - fx_isLocationInsideOtherRegion(in octetstring p_region, in ThreeDLocation p_location) return boolean; - */ - BOOLEAN fx__isLocationInsideOtherRegion(const OCTETSTRING &p_region, const Ieee1609Dot2BaseTypes::ThreeDLocation &p_location) { return TRUE; } - - /** - * \brief Check that p_circular_region_1 circular region is included into p_circular_region_2 circular region - * \param p_circular_region_1 Circular region 1 - * \param p_circular_region_2 Circular region 2 - * \return true on success, false otherwise - fx_areCirclesInside(in CircularRegion p_circular_region_1, in CircularRegion p_circular_region_2) return boolean; - */ - BOOLEAN fx__areCirclesInside(const Ieee1609Dot2BaseTypes::CircularRegion &p_circular_region_1, - const Ieee1609Dot2BaseTypes::CircularRegion &p_circular_region_2) { - // Compute distance between the 2 radius - FLOAT d = LibItsCommon__Functions::fx__computeDistance(p_circular_region_1.center().latitude(), p_circular_region_1.center().longitude(), - p_circular_region_2.center().latitude(), p_circular_region_2.center().longitude()); - if ((float)abs(p_circular_region_1.radius() - p_circular_region_2.radius()) > (float)d) { - return FALSE; - } - return TRUE; - } - - /* * \brief Check that p_rectanglar_region_1 rectangular region is included into p_rectanglar_region_2 rectangular region - * \param p_rectanglar_region_1 Rectangular region 1 - * \param p_rectanglar_region_2 Rectangular region 2 - * \return true on success, false otherwise - fx_areRectanglesInside(in SequenceOfRectangularRegion p_rectanglar_region_1, in SequenceOfRectangularRegion p_rectanglar_region_2) return boolean; - */ - BOOLEAN fx__areRectanglesInside(const Ieee1609Dot2BaseTypes::SequenceOfRectangularRegion &p_rectanglar_region_1, - const Ieee1609Dot2BaseTypes::SequenceOfRectangularRegion &p_rectanglar_region_2) { - - return TRUE; - } - - /* * \brief Check that p_polygonal_region_1 polygonal region is included into p_polygonal_region_2 polygonal region - * \param p_polygonal_region_1 Polygonal region 1 - * \param p_polygonal_region_2 Polygonal region 2 - * \return true on success, false otherwise - fx_arePolygonsInside(in PolygonalRegion p_polygonal_region_1, in PolygonalRegion p_polygonal_region_2) return boolean; - */ - BOOLEAN fx__arePolygonsInside(const Ieee1609Dot2BaseTypes::PolygonalRegion &p_polygonal_region_1, - const Ieee1609Dot2BaseTypes::PolygonalRegion &p_polygonal_region_2) { - return TRUE; - } - - /** - * \brief 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 - fx_dms2dd(in Int p_degrees, in Int p_minutes, in float p_seconds, in Oct1 p_latlon) return float; - */ - FLOAT fx__dms2dd(const INTEGER &p__degrees, const INTEGER &p__minutes, const FLOAT &p__seconds, const OCTETSTRING &p__latlon) { return 0.0; } - - FLOAT fx__int2ddlat(const INTEGER &p__latitude) { return (float)((float)p__latitude / 10000000.0); } - - FLOAT fx__int2ddlon(const INTEGER &p__longitude) { return (float)((float)p__longitude / 1000000.0); } - -} // namespace LibItsSecurity__Functions +/*! + * \file LibItsSecurity_externals.cc + * \brief Source file for Security externl functions. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include + +#include "LibItsCommon_Functions.hh" +#include "LibItsSecurity_Functions.hh" + +#include "hmac.hh" +#include "sha256.hh" +#include "sha384.hh" + +#include "security_ecc.hh" + +#include "security_services.hh" + +#include "geospacial.hh" + +#include +#include + +#include "loggers.hh" + +namespace LibItsSecurity__Functions { + + static std::unique_ptr g(new geospacial); + + // FIXME Unify code with security_services + + /** + * \fn OCTETSTRING fx_hashWithSha256(const OCTETSTRING& p__toBeHashedData); + * \brief Produces a 256-bit (32-bytes) hash value + * \param[in] p__toBeHashedData The data to be used to calculate the hash value + * \return The hash value + */ + OCTETSTRING fx__hashWithSha256(const OCTETSTRING &p__toBeHashedData) { + loggers::get_instance().log_msg(">>> fx__hashWithSha256: p__toBeHashedData= ", p__toBeHashedData); + + sha256 hash; + OCTETSTRING hashData; + hash.generate(p__toBeHashedData, hashData); + loggers::get_instance().log_msg("fx__hashWithSha256: hashData= ", hashData); + return hashData; + } // End of function fx__hashWithSha256 + + /** + * \fn OCTETSTRING fx_hashWithSha384(const OCTETSTRING& p__toBeHashedData); + * \brief Produces a 384-bit (48-bytes) hash value + * \param[in] p__toBeHashedData Data to be used to calculate the hash value + * \return The hash value + */ + OCTETSTRING fx__hashWithSha384(const OCTETSTRING &p__toBeHashedData) { + sha384 hash; + OCTETSTRING hashData; + hash.generate(p__toBeHashedData, hashData); + loggers::get_instance().log_msg("fx__hashWithSha384: hashData= ", hashData); + return hashData; + } // End of function fx__hashWithSha384 + + /** + * \fn OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); + * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2 + * \param[in] p__toBeSignedSecuredMessage The data to be signed + * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate + * \param[in] p__privateKey The private key + * \return The signature value + */ + OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__privateKey) { + loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: data=", p__toBeSignedSecuredMessage); + loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: issuer=", p__certificateIssuer); + loggers::get_instance().log_msg(">>> fx__signWithEcdsaNistp256WithSha256: private key=", p__privateKey); + + // Sanity checks + if ((p__certificateIssuer.lengthof() != 32) || (p__privateKey.lengthof() != 32)) { + loggers::get_instance().log("fx__signWithEcdsaNistp256WithSha256: Wrong parameters"); + return OCTETSTRING(0, nullptr); + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeSignedSecuredMessage, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha256_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash (Data input) || Hash (Signer identifier input)=", hashData1); + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__signWithEcdsaNistp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Calculate the signature + security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashData, r_sig, s_sig) == 0) { + OCTETSTRING os = r_sig + s_sig; + loggers::get_instance().log_msg("r_sig= ", r_sig); + loggers::get_instance().log_msg("s_sig= ", s_sig); + loggers::get_instance().log_msg("sig= ", os); + return os; + } + + return OCTETSTRING(0, nullptr); + } + + /** + * \fn OCTETSTRING fx__signWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); + * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on raw data + * \param[in] p__toBeSignedSecuredMessage The data to be signed + * \param[in] p__privateKey The private key + * \return The signature value + */ + OCTETSTRING fx__test__signWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__privateKey) { + loggers::get_instance().log_msg(">>> fx__test__signWithEcdsaNistp256WithSha256: data=", p__toBeSignedSecuredMessage); + loggers::get_instance().log_msg(">>> fx__test__signWithEcdsaNistp256WithSha256: private key=", p__privateKey); + + // Sanity checks + if (p__privateKey.lengthof() != 32) { + loggers::get_instance().log("fx__test__signWithEcdsaNistp256WithSha256: Wrong parameters"); + return OCTETSTRING(0, nullptr); + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeSignedSecuredMessage, hashData1); + loggers::get_instance().log_msg("fx__test__signWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); + // Calculate the signature + security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashData1, r_sig, s_sig) == 0) { + OCTETSTRING os = r_sig + s_sig; + loggers::get_instance().log_msg("r_sig= ", r_sig); + loggers::get_instance().log_msg("s_sig= ", s_sig); + loggers::get_instance().log_msg("sig= ", os); + return os; + } + + return OCTETSTRING(0, nullptr); + } + + /** + * \fn OCTETSTRING fx__signWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); + * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2 + * \param[in] p__toBeSignedSecuredMessage The data to be signed + * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate + * \param[in] p__privateKey The private key + * \return The signature value + */ + OCTETSTRING fx__signWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__privateKey) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 32) || (p__privateKey.lengthof() != 32)) { + loggers::get_instance().log("fx__signWithEcdsaBrainpoolp256r1WithSha256: Wrong parameters"); + return OCTETSTRING(0, nullptr); + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeSignedSecuredMessage, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha256_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256r1WithSha256: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256r1WithSha256: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp256r1WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Calculate the signature + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__privateKey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashData, r_sig, s_sig) == 0) { + OCTETSTRING os = r_sig + s_sig; + loggers::get_instance().log_msg("r_sig= ", r_sig); + loggers::get_instance().log_msg("s_sig= ", s_sig); + loggers::get_instance().log_msg("sig= ", os); + return os; + } + + return OCTETSTRING(0, nullptr); + } + + /** + * \fn OCTETSTRING fx__signWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING& p__toBeSignedSecuredMessage, const OCTETSTRING& p__privateKey); + * \brief Produces a Elliptic Curve Digital Signature Algorithm (ECDSA) signature based on standard IEEE 1609.2 + * \param[in] p__toBeSignedSecuredMessage The data to be signed + * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate + * \param[in] p__privateKey The private key + * \return The signature value + */ + OCTETSTRING fx__signWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING &p__toBeSignedSecuredMessage, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__privateKey) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 48) || (p__privateKey.lengthof() != 48)) { + loggers::get_instance().log("fx__signWithEcdsaBrainpoolp384r1WithSha384: Wrong parameters"); + return OCTETSTRING(0, nullptr); + } + + // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha384 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeSignedSecuredMessage, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 48)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha384_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Calculate the signature + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__privateKey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashData, r_sig, s_sig) == 0) { + OCTETSTRING os = r_sig + s_sig; + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: r_sig= ", r_sig); + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: s_sig= ", s_sig); + loggers::get_instance().log_msg("fx__signWithEcdsaBrainpoolp384r1WithSha384: sig= ", os); + return os; + } + + return OCTETSTRING(0, nullptr); + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& + * p__ecdsaNistp256PublicKeyCompressed); \brief Verify the signature of the specified data based on standard IEEE 1609.2 \param[in] p__toBeVerifiedData The + * data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate \param[in] + * p__signature The signature \param[in] p__ecdsaNistp256PublicKeyCompressed The compressed public key (x coordinate only) \return true on success, false + * otherwise + */ + BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaNistp256PublicKeyCompressed, + const INTEGER &p__compressedMode) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyCompressed.lengthof() != 32)) { + loggers::get_instance().log("fx__verifyWithEcdsaNistp256WithSha256: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha256_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Check the signature + security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyCompressed, + (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); + if (k.sign_verif(hashData, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__ecdsaNistp256PublicKeyCompressed); + * \brief Verify the signature of the specified data based on raw data + * \param[in] p__toBeVerifiedData The data to be verified + * \param[in] p__signature The signature + * \param[in] p__ecdsaNistp256PublicKeyCompressed The compressed public key (x coordinate only) + * \return true on success, false otherwise + */ + BOOLEAN fx__test__verifyWithEcdsaNistp256WithSha256(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__signature, + const OCTETSTRING &p__ecdsaNistp256PublicKeyCompressed, const INTEGER &p__compressedMode) { + // Sanity checks + if ((p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyCompressed.lengthof() != 32)) { + loggers::get_instance().log("fx__test__verifyWithEcdsaNistp256WithSha256: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + loggers::get_instance().log_msg("fx__test__verifyWithEcdsaNistp256WithSha256: Hash (Data input)=", hashData1); + // Check the signature + security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyCompressed, + (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); + if (k.sign_verif(hashData1, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaNistp256WithSha256_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& + * p__ecdsaNistp256PublicKeyX, const OCTETSTRING& p__ecdsaNistp256PublicKeyY); \brief Verify the signature of the specified data based on standard IEEE 1609.2 + * \param[in] p__toBeVerifiedData The data to be verified + * \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate + * \param[in] p__signature The signature + * \param[in] p__ecdsaNistp256PublicKeyX The public key (x coordinate) + * \param[in] p__ecdsaNistp256PublicKeyY The public key (y coordinate) + * \return true on success, false otherwise + */ + BOOLEAN fx__verifyWithEcdsaNistp256WithSha256__1(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaNistp256PublicKeyX, + const OCTETSTRING &p__ecdsaNistp256PublicKeyY) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaNistp256PublicKeyX.lengthof() != 32) || + (p__ecdsaNistp256PublicKeyY.lengthof() != 32)) { + loggers::get_instance().log("fx__verifyWithEcdsaNistp256WithSha256__1: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha256_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__verifyWithEcdsaNistp256WithSha256__1: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Check the signature + security_ecc k(ec_elliptic_curves::nist_p_256, p__ecdsaNistp256PublicKeyX, p__ecdsaNistp256PublicKeyY); + // security_ecc k(ec_elliptic_curves::nist_p_256); + if (k.sign_verif(hashData, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& + * p__ecdsaBrainpoolp256PublicKeyCompressed); \brief Verify the signature of the specified data based on standard IEEE 1609.2 \param[in] p__toBeVerifiedData + * The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate \param[in] + * p__signature The signature \param[in] p__ecdsaBrainpoolp256PublicKeyCompressed The compressed public key (x coordinate only) \return true on success, false + * otherwise + */ + BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp256PublicKeyCompressed, + const INTEGER &p__compressedMode) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaBrainpoolp256PublicKeyCompressed.lengthof() != 32)) { + loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha256_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Check the signature + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__ecdsaBrainpoolp256PublicKeyCompressed, + (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); + if (k.sign_verif(hashData, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& + * p__ecdsaBrainpoolp256PublicKeyX, const OCTETSTRING& p__ecdsaBrainpoolp256PublicKeyY); \brief Verify the signature of the specified data based on standard + * IEEE 1609.2 \param[in] p__toBeVerifiedData The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in + * case of self signed certificate \param[in] p__signature The signature \param[in] p__ecdsaBrainpoolp256PublicKeyX The public key (x coordinate) \param[in] + * p__ecdsaBrainpoolp256PublicKeyY The public key (y coordinate) \return true on success, false otherwise + */ + BOOLEAN fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp256PublicKeyX, + const OCTETSTRING &p__ecdsaBrainpoolp256PublicKeyY) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 32) || (p__signature.lengthof() != 64) || (p__ecdsaBrainpoolp256PublicKeyX.lengthof() != 32) || + (p__ecdsaBrainpoolp256PublicKeyY.lengthof() != 32)) { + loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA256 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha256 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha256_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp256r1WithSha256__1: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Check the signature + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__ecdsaBrainpoolp256PublicKeyX, p__ecdsaBrainpoolp256PublicKeyY); + if (k.sign_verif(hashData, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& + * p__ecdsaBrainpoolp384PublicKeyCompressed); \brief Verify the signature of the specified data based on standard IEEE 1609.2 \param[in] p__toBeVerifiedData + * The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in case of self signed certificate \param[in] + * p__signature The signature \param[in] p__ecdsaBrainpoolp384PublicKeyCompressed The compressed public key (x coordinate only) \return true on success, false + * otherwise + */ + BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp384PublicKeyCompressed, + const INTEGER &p__compressedMode) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 48) || (p__signature.lengthof() != 96) || (p__ecdsaBrainpoolp384PublicKeyCompressed.lengthof() != 48)) { + loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha384 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 48)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha384_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Check the signature + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__ecdsaBrainpoolp384PublicKeyCompressed, + (p__compressedMode == 0) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1); + if (k.sign_verif(hashData, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384_1(const OCTETSTRING& p__toBeVerifiedData, const OCTETSTRING& p__signature, const OCTETSTRING& + * p__ecdsaBrainpoolp384PublicKeyX, const OCTETSTRING& p__ecdsaBrainpoolp384PublicKeyY); \brief Verify the signature of the specified data based on standard + * IEEE 1609.2 \param[in] p__toBeVerifiedData The data to be verified \param[in] p__certificateIssuer The whole-hash issuer certificate or int2oct(0, 32) in + * case of self signed certificate \param[in] p__signature The signature \param[in] p__ecdsaBrainpoolp384PublicKeyX The public key (x coordinate) \param[in] + * p__ecdsaBrainpoolp384PublicKeyY The public key (y coordinate) \return true on success, false otherwise + */ + BOOLEAN fx__verifyWithEcdsaBrainpoolp384r1WithSha384__1(const OCTETSTRING &p__toBeVerifiedData, const OCTETSTRING &p__certificateIssuer, + const OCTETSTRING &p__signature, const OCTETSTRING &p__ecdsaBrainpoolp384PublicKeyX, + const OCTETSTRING &p__ecdsaBrainpoolp384PublicKeyY) { + // Sanity checks + if ((p__certificateIssuer.lengthof() != 48) || (p__signature.lengthof() != 96) || (p__ecdsaBrainpoolp384PublicKeyX.lengthof() != 48) || + (p__ecdsaBrainpoolp384PublicKeyY.lengthof() != 48)) { + loggers::get_instance().log("fx__verifyWithEcdsaBrainpoolp384r1WithSha384__1: Wrong parameters"); + return FALSE; + } + + // Calculate the SHA384 of the hashed data for signing: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + sha384 hash; + OCTETSTRING hashData1; // Hash (Data input) + hash.generate(p__toBeVerifiedData, hashData1); + OCTETSTRING hashData2; // Hash (Signer identifier input) + if (p__certificateIssuer != int2oct(0, 32)) { // || Hash (Signer identifier input) + hashData2 = p__certificateIssuer; + } else { + hashData2 = hash.get_sha384_empty_string(); // Hash of empty string + } + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Data input)=", hashData1); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash (Signer identifier input)=", hashData2); + hashData1 += hashData2; // Hash (Data input) || Hash (Signer identifier input) + OCTETSTRING hashData; // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + hash.generate(hashData1, hashData); + loggers::get_instance().log_msg("fx__verifyWithEcdsaBrainpoolp384r1WithSha384: Hash ( Hash (Data input) || Hash (Signer identifier input) )=", hashData); + // Check the signature + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__ecdsaBrainpoolp384PublicKeyX, p__ecdsaBrainpoolp384PublicKeyY); + if (k.sign_verif(hashData, p__signature) == 0) { + return TRUE; + } + + return FALSE; + } + + /** + * \fn OCTETSTRING fx__hmac__sha256(const OCTETSTRING& p__k, const OCTETSTRING& p__m); + * \brief Generate a HMAC-SHA256 value based on the provided secret key + * \param[in] p__k The secret key used for the HMAC calculation + * \param[in] p__m The message + * \return The HMAC value resized to 16-byte + */ + OCTETSTRING fx__hmac__sha256(const OCTETSTRING &p__k, const OCTETSTRING &p__m) { + loggers::get_instance().log_msg(">>> fx__hmac__sha256: p__k=", p__k); + loggers::get_instance().log_msg(">>> fx__hmac__sha256: p__m=", p__m); + + hmac h(hash_algorithms::sha_256); // TODO Use ec_encryption_algorithm + OCTETSTRING t; + if (h.generate(p__m, p__k, t) == -1) { + loggers::get_instance().warning("fx__hmac__sha256: Failed to generate HMAC"); + return OCTETSTRING(0, nullptr); + } + + loggers::get_instance().log_msg("<<< fx__hmac__sha256: HMAC: ", t); + return t; + } + + /** + * \fn OCTETSTRING fx__encrypt__aes__128__ccm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt); + * \brief Encrypt the message using AES 128 CCM algorithm + * \param[in] p__k The symmetric encryption key + * \param[in] p__n The initial vector, nonce vector + * \param[in] p__pt The message to encrypt + * \return The encrypted message concatenated to the AES 128 CCM tag + */ + OCTETSTRING fx__encrypt__aes__128__ccm__test(const OCTETSTRING &p__k, const OCTETSTRING &p__n, const OCTETSTRING &p__pt) { + loggers::get_instance().log(">>> fx__encrypt__aes__128__ccm__test"); + + security_ecc ec(ec_elliptic_curves::nist_p_256); + OCTETSTRING enc_message; + if (ec.encrypt(encryption_algotithm::aes_128_ccm, p__k, p__n, p__pt, enc_message) == -1) { + loggers::get_instance().warning("fx__encrypt__aes__128__ccm__test: Failed to encrypt message"); + return OCTETSTRING(0, nullptr); + } + OCTETSTRING os(enc_message + ec.tag()); + loggers::get_instance().log_msg("fx__encrypt__aes__128__ccm__test: encrypted message: ", os); + + return os; + } + + /** + * \fn OCTETSTRING fx__encrypt__aes__128__gcm__test(const OCTETSTRING& p__k, const OCTETSTRING& p__n, const OCTETSTRING& p__pt); + * \brief Encrypt the message using AES 128 GCM algorithm + * \param[in] p__k The symmetric encryption key + * \param[in] p__n The initial vector, nonce vector + * \param[in] p__pt The message to encrypt + * \return The encrypted message concatenated to the AES 128 CCM tag + */ + OCTETSTRING fx__encrypt__aes__128__gcm__test(const OCTETSTRING &p__k, const OCTETSTRING &p__n, const OCTETSTRING &p__pt) { + loggers::get_instance().log(">>> fx__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__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__encrypt__aes__128__gcm__test: encrypted message: ", os); + + return os; + } + + /** + * \fn OCTETSTRING fx__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 + * \param[in] p__k The symmetric encryption key + * \param[in] p__n The initial vector, nonce vector + * \param[in] p__ct The encrypted message concatenated to the AES 128 CCM tag + * \return The original message + */ + OCTETSTRING fx__decrypt__aes__128__ccm__test(const OCTETSTRING &p__k, const OCTETSTRING &p__n, const OCTETSTRING &p__ct) { + loggers::get_instance().log_msg(">>> fx__decrypt__aes__128__ccm__test: p__k: ", p__k); + loggers::get_instance().log_msg(">>> fx__decrypt__aes__128__ccm__test: p__n: ", p__n); + loggers::get_instance().log_msg(">>> fx__decrypt__aes__128__ccm__test: p__ct: ", p__ct); + + security_ecc ec(ec_elliptic_curves::nist_p_256); + // Extract the tag + OCTETSTRING tag(16, p__ct.lengthof() - 16 + static_cast(p__ct)); + loggers::get_instance().log_msg("fx__decrypt__aes__128__ccm__test: tag: ", tag); + // Remove the tag from the end of the encrypted message + OCTETSTRING ct(p__ct.lengthof() - 16, static_cast(p__ct)); + loggers::get_instance().log_msg("fx__decrypt__aes__128__ccm__test: ct: ", ct); + + OCTETSTRING message; + if (ec.decrypt(encryption_algotithm::aes_128_ccm, p__k, p__n, tag, ct, message) == -1) { + loggers::get_instance().warning("fx__decrypt__aes__128__ccm__test: Failed to decrypt message"); + return OCTETSTRING(0, nullptr); + } + loggers::get_instance().log_to_hexa("fx__decrypt__aes__128__ccm__test: decrypted message: ", message); + + return message; + } + + /** + * \fn OCTETSTRING fx__encryptWithEciesNistp256WithSha256(const OCTETSTRING& p__toBeEncryptedSecuredMessage, const OCTETSTRING& p__recipientsPublicKeyX, const + * OCTETSTRING& p__recipientsPublicKeyY, OCTETSTRING& p__publicEphemeralKeyX, OCTETSTRING& p__publicEphemeralKeyY, OCTETSTRING& p__encrypted__sym__key, + * OCTETSTRING& p__authentication__vector, OCTETSTRING& p__nonce); \brief Encrypt the message using ECIES algorithm to encrypt AES 128 CCM symmetric key, as + * defined in IEEE Std 1609.2-2017 \param[in] p__toBeEncryptedSecuredMessage The message to be encrypted \param[in] p__recipientsPublicKeyCompressed The + * Recipient's compressed public key \param[in] p__compressedMode The compressed mode, 0 if the latest bit of Y-coordinate is 0, 1 otherwise \param[out] + * p__publicEphemeralKeyCompressed The public ephemeral compressed key \param[out] p__ephemeralCompressedMode The compressed mode, 0 if the latest bit of + * Y-coordinate is 0, 1 otherwise \param[out] p__encrypted__sym__key The encrypted AES 128 symmetric key \param[out] p__authentication__vector The tag of the + * encrypted AES 128 symmetric key \param[out] p__nonce The nonce vector \return The original message \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key + * encryption algorithms: ECIES \see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/ \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, const OCTETSTRING &p__salt, OCTETSTRING &p__publicEphemeralKeyCompressed, + INTEGER &p__ephemeralCompressedMode, OCTETSTRING &p__aes__sym__key, 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 Ephemeral key + std::unique_ptr ec; + ec.reset(new security_ecc(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 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(), p__salt) == -1) { + loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to generate and derive secret key"); + return OCTETSTRING(0, nullptr); + } + + // Set the AES symmetric key + loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: AES symmetric key: ", ec->symmetric_encryption_key()); + p__aes__sym__key = ec->symmetric_encryption_key(); + loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: p__aes__sym__key: ", p__aes__sym__key); + // Set the encrypted symmetric key + loggers::get_instance().log_msg("fx__encryptWithEciesNistp256WithSha256: Encrypted symmetric key: ", ec->encrypted_symmetric_key()); + p__encrypted__sym__key = ec->encrypted_symmetric_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); + 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); + // 3. Retrieve AES 128 parameters + p__nonce = ec->nonce(); + loggers::get_instance().log_msg("fx__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__encryptWithEciesNistp256WithSha256: Failed to encrypt message"); + return OCTETSTRING(0, nullptr); + } + enc_message += ec->tag(); + loggers::get_instance().log_to_hexa("fx__encryptWithEciesNistp256WithSha256: enc message||Tag: ", enc_message); + + 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__aes__sym__key, 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); + } + + // Set the AES symmetric key + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: AES symmetric key: ", ec.symmetric_encryption_key()); + p__aes__sym__key = ec.symmetric_encryption_key(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: p__aes__sym__key: ", p__aes__sym__key); + // Set the encrypted symmetric key + loggers::get_instance().log_msg("fx__test__encryptWithEciesNistp256WithSha256: Encrypted symmetric key: ", ec.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 \param[in] p__encryptedSecuredMessage The encrypted message \param[in] p__privateEncKey The private encryption key \param[in] + * p__publicEphemeralKeyCompressed The public ephemeral compressed key \param[in] p__ephemeralCompressedMode The compressed mode, 0 if the latest bit of + * Y-coordinate is 0, 1 otherwise \param[in] p__encrypted__sym__key The encrypted AES 128 symmetric key \param[in] p__authentication__vector The tag of the + * encrypted AES 128 symmetric key \param[in] p__nonce The nonce vector \return The original message \see IEEE Std 1609.2-2017 Clause 5.3.5 Public key + * encryption algorithms: ECIES \see https://www.nominet.uk/researchblog/how-elliptic-curve-cryptography-encryption-works/ \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, const OCTETSTRING &p__salt, OCTETSTRING &p__aes__sym__enc__key) { + 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); + loggers::get_instance().log(">>> fx__decryptWithEciesNistp256WithSha256: p__ephemeralCompressedMode: %d", static_cast(p__ephemeralCompressedMode)); + 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 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 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); + } + + // Decrypt the message + OCTETSTRING enc_message(p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof(), + static_cast(p__encryptedSecuredMessage)); // Extract the encrypted message + loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: enc_message: ", enc_message); // Extract the ctag value + OCTETSTRING tag(ec.tag().lengthof(), + static_cast(p__encryptedSecuredMessage) + p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof()); + loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: tag: ", tag); + OCTETSTRING message; + if (ec.decrypt(tag, enc_message, message) == -1) { + loggers::get_instance().warning("fx__decryptWithEciesNistp256WithSha256: Failed to generate shared secret"); + return OCTETSTRING(0, nullptr); + } + loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: dec message: ", message); + p__aes__sym__enc__key = ec.symmetric_encryption_key(); + loggers::get_instance().log_msg("fx__decryptWithEciesNistp256WithSha256: AES 128 encryption key: ", p__aes__sym__enc__key); + + return message; + } + + OCTETSTRING fx__encryptWithEciesBrainpoolp256r1WithSha256(const OCTETSTRING &p__toBeEncryptedSecuredMessage, + const OCTETSTRING &p__recipientsPublicKeyCompressed, const INTEGER &p__compressedMode, + const OCTETSTRING &p__salt, OCTETSTRING &p__publicEphemeralKeyCompressed, + INTEGER &p__ephemeralCompressedMode, OCTETSTRING &p__aes__sym__key, + OCTETSTRING &p__encrypted__sym__key, OCTETSTRING &p__authentication__vector, + OCTETSTRING &p__nonce) { + loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__toBeEncryptedSecuredMessage: ", p__toBeEncryptedSecuredMessage); + loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__recipientsPublicKeyCompressed: ", p__recipientsPublicKeyCompressed); + loggers::get_instance().log(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__compressedMode: %d", static_cast(p__compressedMode)); + loggers::get_instance().log_msg(">>> fx__encryptWithEciesBrainpoolp256r1WithSha256: p__salt: ", p__salt); + + // 1. Generate new Private/Public Ephemeral key + std::unique_ptr ec; + ec.reset(new security_ecc(ec_elliptic_curves::brainpool_p_256_r1)); + if (ec->generate() == -1) { + loggers::get_instance().warning("fx__encryptWithEciesBrainpoolp256r1WithSha256: Failed to generate ephemeral keys"); + return OCTETSTRING(0, nullptr); + } + // 2. Generate and derive shared secret based on recipient's private keys + 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(), p__salt) == -1) { + loggers::get_instance().warning("fx__encryptWithEciesBrainpoolp256r1WithSha256: Failed to generate and derive secret key"); + return OCTETSTRING(0, nullptr); + } + + // Set the AES symmetric key + loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: AES symmetric key: ", ec->symmetric_encryption_key()); + p__aes__sym__key = ec->symmetric_encryption_key(); + loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: p__aes__sym__key: ", p__aes__sym__key); + // Set the encrypted symmetric key + loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: Encrypted symmetric key: ", ec->encrypted_symmetric_key()); + p__encrypted__sym__key = ec->encrypted_symmetric_key(); + loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: p__authentication__vector: ", p__authentication__vector); + // Set ephemeral public keys + p__publicEphemeralKeyCompressed = ec->public_key_compressed(); + loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: Ephemeral public compressed key: ", p__publicEphemeralKeyCompressed); + p__ephemeralCompressedMode = (ec->public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) ? 0 : 1; + loggers::get_instance().log("fx__encryptWithEciesBrainpoolp256r1WithSha256: Ephemeral public compressed mode: %d: ", p__ephemeralCompressedMode); + // 3. Retrieve AES 128 parameters + p__nonce = ec->nonce(); + loggers::get_instance().log_msg("fx__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: Failed to encrypt message"); + return OCTETSTRING(0, nullptr); + } + enc_message += ec->tag(); + loggers::get_instance().log_to_hexa("fx__encryptWithEciesBrainpoolp256r1WithSha256: enc message||Tag: ", enc_message); + + return enc_message; + } + + /** + * @desc Test function for ECIES BRAINPOOL P-256r1 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__encryptWithEciesBrainpoolp256r1WithSha256(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__aes__sym__key, + 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::brainpool_p_256_r1, p__privateEphemeralKey); + p__publicEphemeralKeyX = ec.public_key_x(); + p__publicEphemeralKeyY = ec.public_key_y(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: Vx=", p__publicEphemeralKeyX); + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: Vy=", p__publicEphemeralKeyY); + + // 2. Generate and derive shared secret + security_ecc ec_comp(ec_elliptic_curves::brainpool_p_256_r1, p__recipientPublicKeyX, p__recipientPublicKeyY); + ec.symmetric_encryption_key(p__toBeEncryptedSecuredMessage); + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: ", 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__encryptWithEciesBrainpoolp256r1WithSha256: Failed to generate and derive secret key"); + return OCTETSTRING(0, nullptr); + } + + // Set the AES symmetric key + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: AES symmetric key: ", ec.symmetric_encryption_key()); + p__aes__sym__key = ec.symmetric_encryption_key(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: p__aes__sym__key: ", p__aes__sym__key); + // Set the encrypted symmetric key + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: Encrypted symmetric key: ", ec.encrypted_symmetric_key()); + p__encrypted__sym__key = ec.encrypted_symmetric_key(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: p__authentication__vector: ", p__authentication__vector); + // 3. Retrieve AES 128 parameters + p__nonce = ec.nonce(); + loggers::get_instance().log_msg("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: 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__encryptWithEciesBrainpoolp256r1WithSha256: Failed to encrypt message"); + return OCTETSTRING(0, nullptr); + } + enc_message += ec.tag(); + loggers::get_instance().log_to_hexa("fx__test__encryptWithEciesBrainpoolp256r1WithSha256: enc message||Tag: ", enc_message); + + return enc_message; + } + + OCTETSTRING fx__decryptWithEciesBrainpoolp256r1WithSha256(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, OCTETSTRING &p__aes__sym__enc__key) { + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__toBeEncryptedSecuredMessage: ", p__encryptedSecuredMessage); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__privateEncKey: ", p__privateEncKey); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__publicEphemeralKeyCompressed: ", p__publicEphemeralKeyCompressed); + loggers::get_instance().log(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__ephemeralCompressedMode: %d", + static_cast(p__ephemeralCompressedMode)); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__nonce: ", p__nonce); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__authentication__vector: ", p__authentication__vector); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__encrypted__sym__key: ", p__encrypted__sym__key); + loggers::get_instance().log_msg(">>> fx__decryptWithEciesBrainpoolp256r1WithSha256: p__salt", p__salt); + + // 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 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__decryptWithEciesBrainpoolp256r1WithSha256: Failed to generate shared secret"); + return OCTETSTRING(0, nullptr); + } + + // Decrypt the message + OCTETSTRING enc_message(p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof(), + static_cast(p__encryptedSecuredMessage)); // Extract the encrypted message + loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: enc_message: ", enc_message); // Extract the ctag value + OCTETSTRING tag(ec.tag().lengthof(), + static_cast(p__encryptedSecuredMessage) + p__encryptedSecuredMessage.lengthof() - ec.tag().lengthof()); + loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: tag: ", tag); + OCTETSTRING message; + if (ec.decrypt(tag, enc_message, message) == -1) { + loggers::get_instance().warning("fx__decryptWithEciesBrainpoolp256r1WithSha256: Failed to generate shared secret"); + return OCTETSTRING(0, nullptr); + } + loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: dec message: ", message); + p__aes__sym__enc__key = ec.symmetric_encryption_key(); + loggers::get_instance().log_msg("fx__decryptWithEciesBrainpoolp256r1WithSha256: AES 128 encryption key: ", p__aes__sym__enc__key); + + return message; + } + + /** + * \brief Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm. + * This function should not be used by the ATS + * \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 + fx_generateKeyPair_nistp256(out octetstring p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean; + */ + BOOLEAN fx__generateKeyPair__nistp256(OCTETSTRING &p__privateKey, OCTETSTRING &p__publicKeyX, OCTETSTRING &p__publicKeyY, OCTETSTRING &p__publicKeyCompressed, + INTEGER &p__compressedMode) { + security_ecc k(ec_elliptic_curves::nist_p_256); + if (k.generate() != 0) { + p__privateKey = OCTETSTRING(0, nullptr); + p__publicKeyX = OCTETSTRING(0, nullptr); + p__publicKeyY = OCTETSTRING(0, nullptr); + p__publicKeyCompressed = OCTETSTRING(0, nullptr); + return FALSE; + } + // Sanity checks + if (k.private_key().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid private key size"); + return FALSE; + } + if (k.public_key_x().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public key X-coordonate size"); + return FALSE; + } + if (k.public_key_y().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public key Y-coordonate size"); + return FALSE; + } + if (k.public_key_compressed().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__nistp256: Invalid public compressed key size"); + return FALSE; + } + p__privateKey = k.private_key(); + p__publicKeyX = k.public_key_x(); + p__publicKeyY = k.public_key_y(); + p__publicKeyCompressed = k.public_key_compressed(); + p__compressedMode = INTEGER((int)k.public_key_compressed_mode()); + + return TRUE; + } + + /** + * \brief Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm. + * This function should not be used by the ATS + * \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 + fx_generateKeyPair_nistp256(out octetstring p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean; + */ + BOOLEAN fx__generateKeyPair__brainpoolp256r1(OCTETSTRING &p__privateKey, OCTETSTRING &p__publicKeyX, OCTETSTRING &p__publicKeyY, + OCTETSTRING &p__publicKeyCompressed, INTEGER &p__compressedMode) { + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1); + if (k.generate() != 0) { + p__privateKey = OCTETSTRING(0, nullptr); + p__publicKeyX = OCTETSTRING(0, nullptr); + p__publicKeyY = OCTETSTRING(0, nullptr); + p__publicKeyCompressed = OCTETSTRING(0, nullptr); + return FALSE; + } + + // Sanity checks + if (k.private_key().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid private key size"); + return FALSE; + } + if (k.public_key_x().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid public key X-coordonate size"); + return FALSE; + } + if (k.public_key_y().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid public key Y-coordonate size"); + return FALSE; + } + if (k.public_key_compressed().lengthof() != 32) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp256r1: Invalid public compressed key size"); + return FALSE; + } + p__privateKey = k.private_key(); + p__publicKeyX = k.public_key_x(); + p__publicKeyY = k.public_key_y(); + p__publicKeyCompressed = k.public_key_compressed(); + p__compressedMode = INTEGER((int)k.public_key_compressed_mode()); + + return TRUE; + } + + /** + * \brief Produce a new public/private key pair based on Elliptic Curve Digital Signature Algorithm (ECDSA) algorithm. + * This function should not be used by the ATS + * \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 + fx_generateKeyPair_nistp256(out octetstring p_privateKey, out octetstring p_publicKeyX, out octetstring p_publicKeyY) return boolean; + */ + BOOLEAN fx__generateKeyPair__brainpoolp384r1(OCTETSTRING &p__privateKey, OCTETSTRING &p__publicKeyX, OCTETSTRING &p__publicKeyY, + OCTETSTRING &p__publicKeyCompressed, INTEGER &p__compressedMode) { + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1); + if (k.generate() != 0) { + p__privateKey = OCTETSTRING(0, nullptr); + p__publicKeyX = OCTETSTRING(0, nullptr); + p__publicKeyY = OCTETSTRING(0, nullptr); + p__publicKeyCompressed = OCTETSTRING(0, nullptr); + return FALSE; + } + + // Sanity checks + if (k.private_key().lengthof() != 48) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid private key size"); + return FALSE; + } + if (k.public_key_x().lengthof() != 48) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid public key X-coordonate size"); + return FALSE; + } + if (k.public_key_y().lengthof() != 48) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid public key Y-coordonate size"); + return FALSE; + } + if (k.public_key_compressed().lengthof() != 48) { + loggers::get_instance().error("fx__generateKeyPair__brainpoolp384r1: Invalid public compressed key size"); + return FALSE; + } + p__privateKey = k.private_key(); + p__publicKeyX = k.public_key_x(); + p__publicKeyY = k.public_key_y(); + p__publicKeyCompressed = k.public_key_compressed(); + p__compressedMode = INTEGER((int)k.public_key_compressed_mode()); + + return TRUE; + } + + BOOLEAN fx__get__uncompressed__key__nistp256(const OCTETSTRING &p__privateKey, const OCTETSTRING &p__publicKeyCompressed, const INTEGER &p__compressedMode, + OCTETSTRING &p__publicKeyY) { + security_ecc k(ec_elliptic_curves::nist_p_256, p__privateKey); + + // Sanity checks + if (k.private_key().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid private key size"); + return FALSE; + } + if (k.public_key_x().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public key X-coordonate size"); + return FALSE; + } + if (k.public_key_y().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public key Y-coordonate size"); + return FALSE; + } + if (k.public_key_compressed().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public compressed key size"); + return FALSE; + } + // if (p__compressedMode != INTEGER((int)k.public_key_compressed_mode())) { + // loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public compressed mode"); + // return FALSE; + // } + // if (p__publicKeyCompressed != k.public_key_compressed()) { + // loggers::get_instance().error("fx__get__uncompressed__key__nistp256: Invalid public compressed key value"); + // return FALSE; + // } + + p__publicKeyY = k.public_key_y(); + + return TRUE; + } + + BOOLEAN fx__get__uncompressed__key__brainpoolp256r1(const OCTETSTRING &p__privateKey, const OCTETSTRING &p__publicKeyCompressed, + const INTEGER &p__compressedMode, OCTETSTRING &p__publicKeyY) { + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, p__privateKey); + + // Sanity checks + if (k.private_key().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid private key size"); + return FALSE; + } + if (k.public_key_x().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public key X-coordonate size"); + return FALSE; + } + if (k.public_key_y().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public key Y-coordonate size"); + return FALSE; + } + if (k.public_key_compressed().lengthof() != 32) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public compressed key size"); + return FALSE; + } + // if (p__compressedMode != INTEGER((int)k.public_key_compressed_mode())) { + // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public compressed mode"); + // return FALSE; + // } + // if (p__publicKeyCompressed != k.public_key_compressed()) { + // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp256r1: Invalid public compressed key value"); + // return FALSE; + // } + + p__publicKeyY = k.public_key_y(); + + return TRUE; + } + + BOOLEAN fx__get__uncompressed__key__brainpoolp384r1(const OCTETSTRING &p__privateKey, const OCTETSTRING &p__publicKeyCompressed, + const INTEGER &p__compressedMode, OCTETSTRING &p__publicKeyY) { + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, p__privateKey); + + // Sanity checks + if (k.private_key().lengthof() != 48) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid private key size"); + return FALSE; + } + if (k.public_key_x().lengthof() != 48) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public key X-coordonate size"); + return FALSE; + } + if (k.public_key_y().lengthof() != 48) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public key Y-coordonate size"); + return FALSE; + } + if (k.public_key_compressed().lengthof() != 48) { + loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public compressed key size"); + return FALSE; + } + // if (p__compressedMode != INTEGER((int)k.public_key_compressed_mode())) { + // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public compressed mode"); + // return FALSE; + // } + // if (p__publicKeyCompressed != k.public_key_compressed()) { + // loggers::get_instance().error("fx__get__uncompressed__key__brainpoolp384r1: Invalid public compressed key value"); + // return FALSE; + // } + + p__publicKeyY = k.public_key_y(); + + return TRUE; + } + + // group encryption + + // group certificatesLoader + + /** + * \brief 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 + * @remark This method SHALL be call before any usage of certificates + * \return true on success, false otherwise + fx_loadCertificates(in charstring p_rootDirectory, in charstring p_configId) return boolean; + */ + BOOLEAN fx__loadCertificates(const CHARSTRING &p__rootDirectory, const CHARSTRING &p__configId) { + loggers::get_instance().log(">>> fx__loadCertificates: '%s', '%s'", static_cast(p__rootDirectory), static_cast(p__configId)); + + std::string str(static_cast(p__rootDirectory)); + if (p__configId.lengthof() != 0) { + str += "/"; + str += std::string(static_cast(p__configId)); + } + params params; + params.insert(std::pair(std::string("sec_db_path"), str)); + if (security_services::get_instance().setup(params) == -1) { + return FALSE; + } + + return TRUE; + } + + BOOLEAN fx__store__certificate(const CHARSTRING &p__cert__id, const OCTETSTRING &p__cert, const OCTETSTRING &p__private__key, + const OCTETSTRING &p__public__key__x, const OCTETSTRING &p__public__key__y, const OCTETSTRING &p__public__key__compressed, + const INTEGER &p__public__key__compressed__mode, const OCTETSTRING &p__hash, const OCTETSTRING &p__hash__256, + const OCTETSTRING &p__hashid8, const OCTETSTRING &p__issuer, const OCTETSTRING_template &p__private__enc__key, + const OCTETSTRING_template &p__public__enc__key__x, const OCTETSTRING_template &p__public__enc__key__y, + const OCTETSTRING_template &p__public__enc__compressed__key, const INTEGER_template &p__public__enc__key__compressed__mode) { + loggers::get_instance().log(">>> fx__store__certificate: '%s'", static_cast(p__cert__id)); + + int result; + if (!p__private__enc__key.is_omit()) { + const OCTETSTRING private_enc_key = p__private__enc__key.valueof(); + const OCTETSTRING public_enc_key_x = p__public__enc__key__x.valueof(); + const OCTETSTRING public_enc_key_y = p__public__enc__key__y.valueof(); + result = security_services::get_instance().store_certificate( + p__cert__id, p__cert, p__private__key, p__public__key__x, p__public__key__y, p__public__key__compressed, p__public__key__compressed__mode, p__hash, + p__hash__256, p__hashid8, p__issuer, p__private__enc__key.valueof(), p__public__enc__key__x.valueof(), p__public__enc__key__y.valueof(), + p__public__enc__compressed__key.valueof(), p__public__enc__key__compressed__mode.valueof()); + } else { + result = security_services::get_instance().store_certificate( + p__cert__id, p__cert, p__private__key, p__public__key__x, p__public__key__y, p__public__key__compressed, p__public__key__compressed__mode, p__hash, + p__hash__256, p__hashid8, p__issuer, OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), OCTETSTRING(0, nullptr), INTEGER(-1)); + } + + return (result == 0); + } + + /** + * \brief Unload from memory cache the certificates + * \return true on success, false otherwise + */ + BOOLEAN fx__unloadCertificates() { return TRUE; } + + /** + * \brief Read the specified certificate + * \param p_certificate_id the certificate identifier + * \param p_certificate the expected certificate + * \return true on success, false otherwise + */ + BOOLEAN fx__readCertificate(const CHARSTRING &p__certificateId, OCTETSTRING &p__certificate) { + loggers::get_instance().log(">>> fx__readCertificate: '%s'", static_cast(p__certificateId)); + + if (security_services::get_instance().read_certificate(p__certificateId, p__certificate) == -1) { + return FALSE; + } + + return TRUE; + } + + BOOLEAN fx__readCertificateFromDigest(const OCTETSTRING &p__digest, CHARSTRING &p__certificateId) { + loggers::get_instance().log_msg(">>> fx__readCertificateFromDigest: ", p__digest); + + if (security_services::get_instance().read_certificate_from_digest(p__digest, p__certificateId) == -1) { + return FALSE; + } + loggers::get_instance().log_msg("fx__readCertificateFromDigest: ", p__certificateId); + + return TRUE; + } + + BOOLEAN fx__readCertificateFromHashedId3(const OCTETSTRING &p__digest, CHARSTRING &p__certificateId) { + loggers::get_instance().log_msg(">>> fx__readCertificateFromHashedId3: ", p__digest); + + if (security_services::get_instance().read_certificate_from_hashed_id3(p__digest, p__certificateId) == -1) { + return FALSE; + } + loggers::get_instance().log_msg("fx__readCertificateFromHashedId3: ", p__certificateId); + + return TRUE; + } + + /** + * \brief Read the specified certificate digest + * \param p_certificate_id the certificate identifier + * \param p_digest the expected certificate + * \return true on success, false otherwise + */ + BOOLEAN fx__readCertificateDigest(const CHARSTRING &p__certificateId, OCTETSTRING &p__digest) { + loggers::get_instance().log(">>> fx__readCertificateDigest: '%s'", static_cast(p__certificateId)); + + if (security_services::get_instance().read_certificate_digest(p__certificateId, p__digest) == -1) { + return FALSE; + } + + return TRUE; + } + + /** + * \brief Read the whole-hash of the certificate + * \param p_certificate_id the certificate identifier + * \param p_hash the expected certificate + * \return true on success, false otherwise + */ + BOOLEAN fx__readCertificateHash(const CHARSTRING &p__certificateId, OCTETSTRING &p__hash) { + loggers::get_instance().log(">>> fx__readCertificateHash: '%s'", static_cast(p__certificateId)); + + if (security_services::get_instance().read_certificate_hash(p__certificateId, p__hash) == -1) { + return FALSE; + } + + return TRUE; + } + + /** + * \brief Read the whole-hash of the certificate using SHA 256 + * \param p_certificate_id the certificate identifier + * \param p_hash the expected certificate + * \return true on success, false otherwise + */ + BOOLEAN fx__readCertificateHash256(const CHARSTRING &p__certificateId, OCTETSTRING &p__hash) { + loggers::get_instance().log(">>> fx__readCertificateHash256: '%s'", static_cast(p__certificateId)); + + if (security_services::get_instance().read_certificate_hash_sha_256(p__certificateId, p__hash) == -1) { + return FALSE; + } + + return TRUE; + } + + /** + * \brief Read the private keys for the specified certificate + * \param p_certificate_id the keys identifier + * \param p_signingPrivateKey the signing private key + * \return true on success, false otherwise + */ + BOOLEAN fx__readSigningKey(const CHARSTRING &p__certificateId, OCTETSTRING &p__signingPrivateKey) { + loggers::get_instance().log(">>> fx__readSigningKey: '%s'", static_cast(p__certificateId)); + + if (security_services::get_instance().read_private_key(p__certificateId, p__signingPrivateKey) == -1) { + return FALSE; + } + + return TRUE; + } + + /** + * \brief Read the private keys for the specified certificate + * \param p_keysId the keys identifier + * \param p_encryptPrivateKey the encrypt private key + * \return true on success, false otherwise + fx_readEncryptingKey(in charstring p_keysId, out Oct32 p_encryptingPrivateKey) return boolean; + */ + BOOLEAN fx__readEncryptingKey(const CHARSTRING &p__certificateId, OCTETSTRING &p__encryptingPrivateKey) { + loggers::get_instance().log(">>> fx__readSigningKey: '%s'", static_cast(p__certificateId)); + + if (security_services::get_instance().read_private_enc_key(p__certificateId, p__encryptingPrivateKey) == -1) { + return FALSE; + } + + return TRUE; + } + + // group geospacial + + /* * \brief Check that given polygon doesn't have neither self-intersections nor holes. + * \param p_region Polygonal Region + * \return true on success, false otherwise + * @verdict Unchanged + fx_isValidPolygonalRegion(in PolygonalRegion p_region) return boolean; + */ + BOOLEAN fx__isValidPolygonalRegion(const Ieee1609Dot2BaseTypes::PolygonalRegion &p__region) { return TRUE; } + + /* * \brief Check if a polygonal region 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 + fx_isPolygonalRegionInside(in PolygonalRegion p_parent, in PolygonalRegion p_region) return boolean; + */ + BOOLEAN fx__isPolygonalRegionInside(const Ieee1609Dot2BaseTypes::PolygonalRegion &p__parent, const Ieee1609Dot2BaseTypes::PolygonalRegion &p__region) { + return TRUE; + } + + /* * \brief 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 + fx_isLocationInsideCircularRegion(in CircularRegion p_region, in ThreeDLocation p_location) return boolean; + */ + BOOLEAN fx__isLocationInsideCircularRegion(const Ieee1609Dot2BaseTypes::CircularRegion &p__region, const Ieee1609Dot2BaseTypes::ThreeDLocation &p__location) { + return TRUE; + } + + /* * \brief 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 + fx_isLocationInsideRectangularRegion(in SequenceOfRectangularRegion p_region, in ThreeDLocation p_location) return boolean; + */ + BOOLEAN fx__isLocationInsideRectangularRegion(const Ieee1609Dot2BaseTypes::SequenceOfRectangularRegion &p__region, + const Ieee1609Dot2BaseTypes::ThreeDLocation & p__location) { + return TRUE; + } + + /* * \brief 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 + fx_isLocationInsidePolygonalRegion(in PolygonalRegion p_region, in ThreeDLocation p_location) return boolean; + */ + BOOLEAN fx__isLocationInsidePolygonalRegion(const Ieee1609Dot2BaseTypes::PolygonalRegion &p__region, + const Ieee1609Dot2BaseTypes::ThreeDLocation & p__location) { + return TRUE; + } + + /* * \brief 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 + fx_isLocationInsideIdentifiedRegion(in IdentifiedRegion p_region, in ThreeDLocation p_location) return boolean; + */ + BOOLEAN fx__isLocationInsideIdentifiedRegion(const Ieee1609Dot2BaseTypes::IdentifiedRegion &p__region, + const Ieee1609Dot2BaseTypes::ThreeDLocation & p__location) { + return TRUE; + } + + /* * \brief Check if the location is inside an undefined region + * \param p_region The identified region to consider + * \param p_location The device location + * \return true on success, false otherwise + * @verdict Unchanged + fx_isLocationInsideOtherRegion(in octetstring p_region, in ThreeDLocation p_location) return boolean; + */ + BOOLEAN fx__isLocationInsideOtherRegion(const OCTETSTRING &p_region, const Ieee1609Dot2BaseTypes::ThreeDLocation &p_location) { return TRUE; } + + /** + * \brief Check that p_circular_region_1 circular region is included into p_circular_region_2 circular region + * \param p_circular_region_1 Circular region 1 + * \param p_circular_region_2 Circular region 2 + * \return true on success, false otherwise + fx_areCirclesInside(in CircularRegion p_circular_region_1, in CircularRegion p_circular_region_2) return boolean; + */ + BOOLEAN fx__areCirclesInside(const Ieee1609Dot2BaseTypes::CircularRegion &p_circular_region_1, + const Ieee1609Dot2BaseTypes::CircularRegion &p_circular_region_2) { + // Compute distance between the 2 radius + FLOAT d = LibItsCommon__Functions::fx__computeDistance(p_circular_region_1.center().latitude(), p_circular_region_1.center().longitude(), + p_circular_region_2.center().latitude(), p_circular_region_2.center().longitude()); + if ((float)abs(p_circular_region_1.radius() - p_circular_region_2.radius()) > (float)d) { + return FALSE; + } + return TRUE; + } + + /* * \brief Check that p_rectanglar_region_1 rectangular region is included into p_rectanglar_region_2 rectangular region + * \param p_rectanglar_region_1 Rectangular region 1 + * \param p_rectanglar_region_2 Rectangular region 2 + * \return true on success, false otherwise + fx_areRectanglesInside(in SequenceOfRectangularRegion p_rectanglar_region_1, in SequenceOfRectangularRegion p_rectanglar_region_2) return boolean; + */ + BOOLEAN fx__areRectanglesInside(const Ieee1609Dot2BaseTypes::SequenceOfRectangularRegion &p_rectanglar_region_1, + const Ieee1609Dot2BaseTypes::SequenceOfRectangularRegion &p_rectanglar_region_2) { + + return TRUE; + } + + /* * \brief Check that p_polygonal_region_1 polygonal region is included into p_polygonal_region_2 polygonal region + * \param p_polygonal_region_1 Polygonal region 1 + * \param p_polygonal_region_2 Polygonal region 2 + * \return true on success, false otherwise + fx_arePolygonsInside(in PolygonalRegion p_polygonal_region_1, in PolygonalRegion p_polygonal_region_2) return boolean; + */ + BOOLEAN fx__arePolygonsInside(const Ieee1609Dot2BaseTypes::PolygonalRegion &p_polygonal_region_1, + const Ieee1609Dot2BaseTypes::PolygonalRegion &p_polygonal_region_2) { + return TRUE; + } + + /** + * \brief 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 + fx_dms2dd(in Int p_degrees, in Int p_minutes, in float p_seconds, in Oct1 p_latlon) return float; + */ + FLOAT fx__dms2dd(const INTEGER &p__degrees, const INTEGER &p__minutes, const FLOAT &p__seconds, const OCTETSTRING &p__latlon) { return 0.0; } + + FLOAT fx__int2ddlat(const INTEGER &p__latitude) { return (float)((float)p__latitude / 10000000.0); } + + FLOAT fx__int2ddlon(const INTEGER &p__longitude) { return (float)((float)p__longitude / 1000000.0); } + +} // namespace LibItsSecurity__Functions diff --git a/ccsrc/Externals/module.mk b/ccsrc/Externals/module.mk index 96e780284204f6f98f0b5052a5f685bfffae1c59..f0b5fac359de5e1ed0f636e80b45ce024c993f92 100644 --- a/ccsrc/Externals/module.mk +++ b/ccsrc/Externals/module.mk @@ -13,6 +13,10 @@ ifeq (AtsDENM, $(ATS)) sources += LibItsSecurity_externals.cc endif +ifeq (AtsIS, $(ATS)) +sources += LibItsSecurity_externals.cc +endif + ifeq (AtsSecurity, $(ATS)) sources += LibItsSecurity_externals.cc endif @@ -25,6 +29,10 @@ ifeq (AtsGeoNetworking, $(ATS)) sources += LibItsSecurity_externals.cc endif +ifeq (AtsIPv6OverGeoNetworking, $(ATS)) +sources += LibItsSecurity_externals.cc +endif + ifeq (AtsBTP, $(ATS)) sources += LibItsSecurity_externals.cc endif diff --git a/ccsrc/Framework/include/base_time.hh b/ccsrc/Framework/include/base_time.hh index 93668584900e0b1df8ef7838ae554f78cc155fc9..03fa8f6cd453f1ed6bcde16fff8b47b86b7a9ecf 100644 --- a/ccsrc/Framework/include/base_time.hh +++ b/ccsrc/Framework/include/base_time.hh @@ -1,73 +1,73 @@ -/*! - * \file base_time.hh - * \brief Header file for the control port base_time functionality. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -/** - * \class base_time - * \brief This class provides time tools such as getting current time - */ -class base_time { - const unsigned long long its_base_time_ms = 1072915200000L; //! Base time 01/01/2004 12:00am in millseconds - - unsigned long long leap_delay; - - static base_time *_instance; - -private: - base_time() : leap_delay{0} {}; //! Can not be created manually -public: - static inline base_time &get_instance(); - - virtual ~base_time() { - if (_instance != nullptr) - delete _instance; - }; - -public: - inline const unsigned long long get_current_time_ms() const; - inline const unsigned long long get_its_base_time_ms() const; - inline const unsigned long long get_its_current_time_ms() const; - inline const unsigned long long get_its_current_time_us() const; - inline const unsigned long long get_its_current_time_mod_ms() const; - inline void set_leap_delay_us(const unsigned long long p_leap_delay); - inline const unsigned long long get_leap_delay_us() const; -}; // End of class base_time - -// static functions -base_time &base_time::get_instance() { return (_instance != nullptr) ? *_instance : *(_instance = new base_time()); } - -const unsigned long long base_time::get_current_time_ms() const { - return (leap_delay / 1000) + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); -} - -const unsigned long long base_time::get_its_base_time_ms() const { return base_time::its_base_time_ms; } - -const unsigned long long base_time::get_its_current_time_ms() const { - return (leap_delay / 1000) + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() - - base_time::its_base_time_ms; -} - -const unsigned long long base_time::get_its_current_time_us() const { - return leap_delay + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() - - base_time::its_base_time_ms * 1000; -} - -const unsigned long long base_time::get_its_current_time_mod_ms() const { - return ((leap_delay / 1000) + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() - - base_time::its_base_time_ms) % - 65536; -} - -void base_time::set_leap_delay_us(const unsigned long long p_leap_delay) { leap_delay = p_leap_delay; } - -inline const unsigned long long base_time::get_leap_delay_us() const { return leap_delay; } +/*! + * \file base_time.hh + * \brief Header file for the control port base_time functionality. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +/** + * \class base_time + * \brief This class provides time tools such as getting current time + */ +class base_time { + const unsigned long long its_base_time_ms = 1072915200000L; //! Base time 01/01/2004 12:00am in millseconds + + unsigned long long leap_delay; + + static base_time *_instance; + +private: + base_time() : leap_delay{0} {}; //! Can not be created manually +public: + static inline base_time &get_instance(); + + virtual ~base_time() { + if (_instance != nullptr) + delete _instance; + }; + +public: + inline const unsigned long long get_current_time_ms() const; + inline const unsigned long long get_its_base_time_ms() const; + inline const unsigned long long get_its_current_time_ms() const; + inline const unsigned long long get_its_current_time_us() const; + inline const unsigned long long get_its_current_time_mod_ms() const; + inline void set_leap_delay_us(const unsigned long long p_leap_delay); + inline const unsigned long long get_leap_delay_us() const; +}; // End of class base_time + +// static functions +base_time &base_time::get_instance() { return (_instance != nullptr) ? *_instance : *(_instance = new base_time()); } + +const unsigned long long base_time::get_current_time_ms() const { + return (leap_delay / 1000) + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} + +const unsigned long long base_time::get_its_base_time_ms() const { return base_time::its_base_time_ms; } + +const unsigned long long base_time::get_its_current_time_ms() const { + return (leap_delay / 1000) + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() - + base_time::its_base_time_ms; +} + +const unsigned long long base_time::get_its_current_time_us() const { + return leap_delay + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() - + base_time::its_base_time_ms * 1000; +} + +const unsigned long long base_time::get_its_current_time_mod_ms() const { + return ((leap_delay / 1000) + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count() - + base_time::its_base_time_ms) % + 65536; +} + +void base_time::set_leap_delay_us(const unsigned long long p_leap_delay) { leap_delay = p_leap_delay; } + +inline const unsigned long long base_time::get_leap_delay_us() const { return leap_delay; } diff --git a/ccsrc/Framework/include/codec.hh b/ccsrc/Framework/include/codec.hh index 7a8c4a240edb18ee6ea44bb63218c59a8ed76db7..912293bf80429bfc34e646fe501e7eeca66cf28c 100644 --- a/ccsrc/Framework/include/codec.hh +++ b/ccsrc/Framework/include/codec.hh @@ -1,61 +1,61 @@ -/*! - * \file codec.hh - * \brief Header file for ITS abstract codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "params.hh" - -class OCTETSTRING; //! Declare TITAN class -class CHARSTRING; //! Declare TITAN class -class BITSTRING; //! Declare TITAN class - -/*! - * \class codec - * \brief This class provides the interface for all ITS codecs, include UT and AC codecs - * \abstract - */ -template class codec { -protected: - params *_params; //! Reference to params stack - // \todo Use smart pointer std::unique_ptr - -public: //! \publicsection - /*! - * \fn codec(); - * \brief Default constructor - * \todo Remove logs - */ - explicit codec() : _params(nullptr){}; - /*! - * \fn ~codec(); - * \brief Default destructor - * \virtual - * \todo Remove logs - */ - virtual ~codec(){}; - /*! - * \fn int encode(const TPDUEnc& msg, OCTETSTRING& data); - * \brief Encode typed message into an octet string - * \param[in] p_message The typed message to be encoded - * \param[out] p_data The encoding result - * \return 0 on success, -1 otherwise - * \pure - */ - virtual int encode(const TPDUEnc &p_message, OCTETSTRING &p_data) = 0; - /*! - * \fn int decode(const OCTETSTRING& p_, TPDUDec& p_message, params* p_params = NULL); - * \brief Encode typed message into an octet string format - * \param[in] p_data The message in its octet string - * \param[out] p_message The decoded typed message - * \return 0 on success, -1 otherwise - * \pure - */ - virtual int decode(const OCTETSTRING &p_, TPDUDec &p_message, params *p_params = NULL) = 0; -}; // End of class codec +/*! + * \file codec.hh + * \brief Header file for ITS abstract codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "params.hh" + +class OCTETSTRING; //! Declare TITAN class +class CHARSTRING; //! Declare TITAN class +class BITSTRING; //! Declare TITAN class + +/*! + * \class codec + * \brief This class provides the interface for all ITS codecs, include UT and AC codecs + * \abstract + */ +template class codec { +protected: + params *_params; //! Reference to params stack + // \todo Use smart pointer std::unique_ptr + +public: //! \publicsection + /*! + * \fn codec(); + * \brief Default constructor + * \todo Remove logs + */ + explicit codec() : _params(nullptr){}; + /*! + * \fn ~codec(); + * \brief Default destructor + * \virtual + * \todo Remove logs + */ + virtual ~codec(){}; + /*! + * \fn int encode(const TPDUEnc& msg, OCTETSTRING& data); + * \brief Encode typed message into an octet string + * \param[in] p_message The typed message to be encoded + * \param[out] p_data The encoding result + * \return 0 on success, -1 otherwise + * \pure + */ + virtual int encode(const TPDUEnc &p_message, OCTETSTRING &p_data) = 0; + /*! + * \fn int decode(const OCTETSTRING& p_, TPDUDec& p_message, params* p_params = NULL); + * \brief Encode typed message into an octet string format + * \param[in] p_data The message in its octet string + * \param[out] p_message The decoded typed message + * \return 0 on success, -1 otherwise + * \pure + */ + virtual int decode(const OCTETSTRING &p_, TPDUDec &p_message, params *p_params = NULL) = 0; +}; // End of class codec diff --git a/ccsrc/Framework/include/codec_factory.hh b/ccsrc/Framework/include/codec_factory.hh index e63dfe7822e6248a33995039b6e019490729a164..037247aef3b5198f4692082fd28c085883ba73c7 100644 --- a/ccsrc/Framework/include/codec_factory.hh +++ b/ccsrc/Framework/include/codec_factory.hh @@ -1,45 +1,45 @@ -/*! - * \file codec_factory.hh - * \brief Header file for ITS abstract protocol codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -#include "codec.hh" - -class Record_Type; //! TITAN forward declaration - -/*! - * \class codec_factory - * \brief This class provides a factory class to create codec class instances - * \abstract - */ -class codec_factory { -public: //! \publicsection - /*! - * \fn codec(); - * \brief Default constructor - */ - codec_factory(){}; - /*! - * \fn codec* create_codec(const std::string & type, const std::string & param); - * \brief Create the codecs stack based on the provided codecs stack description (cf. remark) - * \param[in] p_type The provided codecs stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \remark The description below introduces codecs stack in case of ITS project: - * HTTP(codecs=xml:held_codec;html:html_codec,json:json_codec)/TCP(debug=1,server=httpbin.org,port=80,use_ssl=0) - * \pure - */ - virtual codec *create_codec() = 0; -}; // End of class codec_factory +/*! + * \file codec_factory.hh + * \brief Header file for ITS abstract protocol codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +#include "codec.hh" + +class Record_Type; //! TITAN forward declaration + +/*! + * \class codec_factory + * \brief This class provides a factory class to create codec class instances + * \abstract + */ +class codec_factory { +public: //! \publicsection + /*! + * \fn codec(); + * \brief Default constructor + */ + codec_factory(){}; + /*! + * \fn codec* create_codec(const std::string & type, const std::string & param); + * \brief Create the codecs stack based on the provided codecs stack description (cf. remark) + * \param[in] p_type The provided codecs stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \remark The description below introduces codecs stack in case of ITS project: + * HTTP(codecs=xml:held_codec;html:html_codec,json:json_codec)/TCP(debug=1,server=httpbin.org,port=80,use_ssl=0) + * \pure + */ + virtual codec *create_codec() = 0; +}; // End of class codec_factory diff --git a/ccsrc/Framework/include/codec_stack_builder.hh b/ccsrc/Framework/include/codec_stack_builder.hh index cd3ab834f379df700487dbb382dad48f3e3b2485..e3440de459a0115b2859a6dfefca2d4e3dd9692e 100644 --- a/ccsrc/Framework/include/codec_stack_builder.hh +++ b/ccsrc/Framework/include/codec_stack_builder.hh @@ -1,75 +1,75 @@ -/*! - * \file codec_stack_builder.hh - * \brief Header file for ITS protocol stack builder. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "codec_factory.hh" - -class Record_Type; //! TITAN forward declaration - -/*! - * \class codec_stack_builder - * \brief This class provides a factory class to create Codec class instances - */ -class codec_stack_builder { -private: //! \privatesection - static codec_stack_builder * _instance; //! Smart pointer to the unique instance of the logger framework - std::map _codecs; //! The list of the registered \see t_codec factories - - /*! - * \brief Default constructor - * Create a new instance of the codec_stack_builder class - * \private - */ - codec_stack_builder(){}; // can not be created manually -public: //! \publicsection - /*! - * \fn codec_stack_builder* get_instance(); - * \brief Accessor for the unique instance of the logger framework - * \static - */ - static codec_stack_builder *get_instance() { return _instance ? _instance : _instance = new codec_stack_builder(); }; - - /*! - * \fn void register_codec_factory(const std::string & p_type, codec_factory* p_codec_factory); - * \brief Add a new codec factory - * \param[in] p_type The codec identifier (e.g. GN for the GeoNetworking codec...) - * \param[in] p_codec_factory A reference to the \see codec_factory - * \static - */ - static void register_codec_factory(const std::string &p_type, codec_factory *p_codec_factory) { - codec_stack_builder::get_instance()->_register_codec_factory(p_type, p_codec_factory); - }; - -private: //! \privatesection - /*! - * \fn void _register_codec_factory(const std::string & p_type, codec_factory* p_codec_factory); - * \brief Add a new codec factory - * \param[in] p_type The codec identifier (e.g. GN for the GeoNetworking codec...) - * \param[in] p_codec_factory A reference to the \see codec_factory - */ - void _register_codec_factory(const std::string &p_type, codec_factory *p_codec_factory) { _codecs[p_type] = p_codec_factory; }; - -public: //! \publicsection - /*! - * \fn codec* get_codec(const char* p_codec_name); - * \brief Retrieve the specified codec name from the list of the registered codecs - * \param[in] p_codec_name The codec indentifier - * \return The pointer to the codec object on success, nullptr otherwise - */ - inline codec *get_codec(const char *p_codec_name) { // NOTE A virtual method cannot not be a template ==> polymorphism required here - typename std::map::const_iterator it = _codecs.find(p_codec_name); - if (it != _codecs.cend()) { - return it->second->create_codec(); - } - - return nullptr; - } -}; // End of class codec_stack_builder +/*! + * \file codec_stack_builder.hh + * \brief Header file for ITS protocol stack builder. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "codec_factory.hh" + +class Record_Type; //! TITAN forward declaration + +/*! + * \class codec_stack_builder + * \brief This class provides a factory class to create Codec class instances + */ +class codec_stack_builder { +private: //! \privatesection + static codec_stack_builder * _instance; //! Smart pointer to the unique instance of the logger framework + std::map _codecs; //! The list of the registered \see t_codec factories + + /*! + * \brief Default constructor + * Create a new instance of the codec_stack_builder class + * \private + */ + codec_stack_builder(){}; // can not be created manually +public: //! \publicsection + /*! + * \fn codec_stack_builder* get_instance(); + * \brief Accessor for the unique instance of the logger framework + * \static + */ + static codec_stack_builder *get_instance() { return _instance ? _instance : _instance = new codec_stack_builder(); }; + + /*! + * \fn void register_codec_factory(const std::string & p_type, codec_factory* p_codec_factory); + * \brief Add a new codec factory + * \param[in] p_type The codec identifier (e.g. GN for the GeoNetworking codec...) + * \param[in] p_codec_factory A reference to the \see codec_factory + * \static + */ + static void register_codec_factory(const std::string &p_type, codec_factory *p_codec_factory) { + codec_stack_builder::get_instance()->_register_codec_factory(p_type, p_codec_factory); + }; + +private: //! \privatesection + /*! + * \fn void _register_codec_factory(const std::string & p_type, codec_factory* p_codec_factory); + * \brief Add a new codec factory + * \param[in] p_type The codec identifier (e.g. GN for the GeoNetworking codec...) + * \param[in] p_codec_factory A reference to the \see codec_factory + */ + void _register_codec_factory(const std::string &p_type, codec_factory *p_codec_factory) { _codecs[p_type] = p_codec_factory; }; + +public: //! \publicsection + /*! + * \fn codec* get_codec(const char* p_codec_name); + * \brief Retrieve the specified codec name from the list of the registered codecs + * \param[in] p_codec_name The codec indentifier + * \return The pointer to the codec object on success, nullptr otherwise + */ + inline codec *get_codec(const char *p_codec_name) { // NOTE A virtual method cannot not be a template ==> polymorphism required here + typename std::map::const_iterator it = _codecs.find(p_codec_name); + if (it != _codecs.cend()) { + return it->second->create_codec(); + } + + return nullptr; + } +}; // End of class codec_stack_builder diff --git a/ccsrc/Framework/include/converter.hh b/ccsrc/Framework/include/converter.hh index 428791fbb8b85440d43e6aaae95c898debba043a..6070f2d80e6bdf0ec4cb089b102fc9e9177c43f0 100644 --- a/ccsrc/Framework/include/converter.hh +++ b/ccsrc/Framework/include/converter.hh @@ -1,387 +1,387 @@ -/*! - * \file converter.hh - * \brief Helper class for types converter. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include - -#include -#include -#include - -#include -#include // LONG_MAX, LLONG_MAX -#include -#include // time_t, struct tm, difftime, time, mktime - -/*! - * \class converter - * \brief This class provide a set of methods for types conversions - * \remark Singleton pattern - */ -class converter { - - /*! - * \brief Unique static object reference of this class - */ - static converter *instance; - - /*! - * \brief Default private ctor - */ - converter(){}; - /*! - * \brief Default private dtor - */ - ~converter() { - if (instance != NULL) { - delete instance; - instance = NULL; - } - }; - -public: /*! \publicsection */ - /*! - * \brief Public accessor to the single object reference - */ - inline static converter &get_instance() { - if (instance == NULL) - instance = new converter(); - return *instance; - }; - -public: - /*! - * \enum endian_t - * \brief Endianess style - */ - typedef enum { big_endian, little_endian } endian_t; - -public: - /*! - * \brief Convert a Binary Coded Decimal value into a binary value - * \param[in] p_value The BDC value - * \return The binary value - * \inline - */ - inline uint8_t bcd_to_bin(const uint8_t p_value) { return ((p_value / 16 * 10) + (p_value % 16)); }; - - /*! - * \brief Convert a binary value into a Binary Coded Decimal value - * \param[in] p_value The binary value - * \return The BCD value - * \inline - */ - inline uint8_t bin_to_bcd(const uint8_t p_value) { return ((p_value / 10 * 16) + (p_value % 10)); }; - - /*! - * \brief Swap two bytes length value (e.g. 0xCAFE becomes 0xFECA) - * \param[in] p_value The value to swap - * \return The swapped value - * \inline - */ - uint16_t swap(const uint16_t p_value); - inline int16_t swap(const int16_t p_value) { return static_cast(swap(static_cast(p_value))); }; - /*! - * \brief Swap four bytes length value (used for littel endian / big endian) - * \param[in] p_value The value to swap - * \return The swapped value - */ - uint32_t swap(const uint32_t p_value); - inline int32_t swap(const int32_t p_value) { return static_cast(swap(static_cast(p_value))); }; - - /*! - * \brief Convert a string into an hexadecimal string - * \param[in] p_value The string value - * \return The hexadecimal value - */ - std::string string_to_hexa(const std::string &p_value, const bool p_uppercase = false); - /*! - * \brief Convert a bytes array int32_t an hexadecimal string - * \param[in] p_value The bytes array value - * \return The hexadecimal value - */ - std::string bytes_to_hexa(const std::vector &p_value, const bool p_uppercase = false); - /*! - * \brief Convert an hexadecimal string into a bytes array - * \param[in] p_value The hexadecimal value - * \return The bytes array value - */ - std::vector hexa_to_bytes(const std::string &p_value); - - /*! - * \brief Convert a time in time_t format into a string formated according to RFC 822, 1036, 1123, 2822 - * \param[in] p_time The time to convert in time_t format - * \return The time string formated - * \see http://www.unixtimestamp.com/ - * @code - * std::string result = time_to_string(1489755780); - * result.compare("Fri, 17 Mar 2017 13:03:00 +0000") == 0 // When time zone is set to UTC - * @endcode - * \remark Use commands 1) timedatectl to change your machine timezone (e.g. sudo timedatectl set-timezone UTC to change machine timezone to UTC, 2) - * timedatectl list-timezones to get the list of the timezones) - */ - std::string time_to_string(const time_t p_time); - /*! - * \brief Convert a time in struct tm format into a string formated according to RFC 822, 1036, 1123, 2822 - * \param[in] p_time The time to convert in struct tm format - * \return The time string formated - * \see http://www.unixtimestamp.com/ - */ - std::string time_to_string(const struct tm &p_time); - - /*! - * \brief Convert a 16-bits integer (int16_t) into a bytes array - * \param[in] p_value The 16-bits integer value - * \param[in] p_endianess Endianess style. Default: big_endian - * \return The bytes array value - */ - inline std::vector short_to_bytes(const int16_t p_value, const endian_t p_endianess = big_endian) const { - std::vector result(sizeof(short), 0x00); - for (int i = sizeof(short) - 1; i >= 0; i--) { - int offset = (sizeof(short) - 1 - i) * 8; - result[i] = static_cast((p_value >> offset) & 0xFF); - } // End of 'for' statement - return result; - }; // End of short_to_bytes - - /*! - * \brief Convert a bytes array into a 16-bits integer (int16_t) - * \param[in] p_value The bytes array - * \param[in] p_endianess Endianess style. Default: big_endian - * \return The 16-bits integer on success, SHRT_MAX on error (wrong bytes array size) - */ - inline int16_t bytes_to_short(const std::vector &p_value, const endian_t p_endianess = big_endian) const { - // Sanity check - if (p_value.size() > sizeof(short)) { - return SHRT_MAX; - } - int16_t value = 0; - for (size_t i = 0; i < p_value.size(); i++) { - value = (value << 8) + (p_value[i] & 0xff); - } // End of 'for' statement - return value; - }; // End of bytes_to_short - - /*! - * \brief Convert a 32-bits integer (int32_t) into a bytes array - * \param[in] p_value The 32-bits integer value - * \param[in] p_endianess Endianess style. Default: big_endian - * \return The bytes array value - */ - inline std::vector int_to_bytes(const int32_t p_value, const endian_t p_endianess = big_endian) const { - /*uint8_t bytes[sizeof(p_value)]; - std::copy( - static_cast(static_cast(&p_value)), - static_cast(static_cast(&p_value)) + sizeof(p_value), - bytes - ); - std::vector result(bytes, bytes + sizeof(bytes) / sizeof(uint8_t));*/ - std::vector result(sizeof(int), 0x00); - for (int i = sizeof(int) - 1; i >= 0; i--) { - int offset = (sizeof(int) - 1 - i) * 8; - result[i] = static_cast((p_value >> offset) & 0xFF); - } // End of 'for' statement - return result; - }; // End of int_to_bytes - - /*! - * \brief Convert a bytes array into a 32-bits integer (int32_t) - * \param[in] p_value The bytes array - * \param[in] p_endianess Endianess style. Default: big_endian - * \return The 32-bits integer on success, LONG_MAX on error (wrong bytes array size) - */ - inline int32_t bytes_to_int(const std::vector &p_value, const endian_t p_endianess = big_endian) const { - // Sanity check - if (p_value.size() > sizeof(int)) { - return INT_MAX; - } - int32_t value = 0; - for (size_t i = 0; i < p_value.size(); i++) { - value = (value << 8) + (p_value[i] & 0xff); - } // End of 'for' statement - return value; - // return *((int *)(&p_value[0])); - }; // End of bytes_to_int - - /*! - * \brief Convert a 64-bits integer (int64_t) into a bytes array - * \param[in] p_value The 64-bits integer value - * \param[in] p_endianess Endianess style. Default: big_endian - * \return The bytes array value - */ - inline std::vector long_to_bytes(const int64_t p_value, const endian_t p_endianess = big_endian) const { - /*uint8_t bytes[sizeof(p_value)]; - std::copy( - static_cast(static_cast(&p_value)), - static_cast(static_cast(&p_value)) + sizeof(p_value), - bytes - ); - std::vector result(bytes, bytes + sizeof(bytes) / sizeof(uint8_t));*/ - std::vector result(sizeof(int64_t), 0x00); - for (int i = sizeof(int64_t) - 1; i >= 0; i--) { - int offset = (sizeof(int64_t) - 1 - i) * 8; - result[i] = static_cast((p_value >> offset) & 0xFF); - } // End of 'for' statement - return result; - }; // End of long_to_bytes - - /*! - * \brief Convert a bytes array into a 64-bits integer (int64_t) - * \param[in] p_value The bytes array - * \param[in] p_endianess Endianess style. Default: big_endian - * \return The 64-bits integer on success, LLONG_MAX on error (wrong bytes array size) - */ - inline int64_t bytes_to_long(const std::vector &p_value, const endian_t p_endianess = big_endian) const { - // Sanity check - if (p_value.size() > sizeof(int64_t)) { - return LLONG_MAX; - } - int64_t value = 0; - for (size_t i = 0; i < p_value.size(); i++) { - value = (value << 8) + (p_value[i] & 0xff); - } // End of 'for' statement - return value; - // return *((long *)(&p_value[0])); - }; // End of bytes_to_long - - /*! - * \brief Convert a float value into a bytes array - * \param[in] p_value The float value - * \return The bytes array value - */ - inline std::vector float_to_bytes(const float p_value) const { - uint8_t bytes[sizeof(p_value)]; - std::copy(static_cast(static_cast(&p_value)), - static_cast(static_cast(&p_value)) + sizeof(p_value), bytes); - std::vector result(bytes, bytes + sizeof(bytes) / sizeof(uint8_t)); - return result; - }; // End of float_to_long - - /*! - * \brief Convert a bytes array into a float - * \param[in] p_value The bytes array - * \return The float value - */ - inline float bytes_to_float(const std::vector &p_value) const { return *((float *)(&p_value[0])); }; // End of bytes_to_float - - /*! - * \brief Convert a string into a bytes array - * \param[in] p_value The string value - * \return The bytes array value - */ - inline std::vector string_to_bytes(const std::string &p_value) const { - return std::vector(p_value.begin(), p_value.end()); - }; // End of string_to_bytes - - /*! - * \brief Convert a bytes array into a string - * \param[in] p_value The bytes array value - * \return The string value - */ - inline std::string bytes_to_string(const std::vector &p_value) const { - return std::string(p_value.begin(), p_value.end()); - }; // End of bytes_to_string - -public: - /*! - * \brief Convert a string into an integer - * \param[in] p_value The string value - * \return The integer value - */ - inline int32_t string_to_int(const std::string &p_value) const { - return std::stoi(p_value); - // return atoi(p_value.c_str()); - }; // End of string_to_int - - /*! - * \brief Convert an integer into a string - * \param[in] p_value The integer value - * \return The string value - */ - inline std::string int_to_string(const int32_t &p_value) const { - std::ostringstream ss; - ss << p_value; - return ss.str(); - }; // End of string_to_bytes - - /*! - * \brief Convert a string in to lower case - * \param[in/out] p_value The string value to convert - */ - inline void to_lower(std::string &p_value) { std::transform(p_value.begin(), p_value.end(), p_value.begin(), ::tolower); } - - /*! - * \brief Convert a string in to upper case - * \param[in/out] p_value The string value to convert - */ - inline void to_upper(std::string &p_value) { std::transform(p_value.begin(), p_value.end(), p_value.begin(), ::toupper); } - -public: - /*! - * \brief Returns a copy of the string, with leading and trailing special characters omitted - * \param[in] p_value The string value - * \param[in] p_trim_chars The special characters to be omitted. Default: ' ' and TAB - * \return The new string value - */ - std::string trim(const std::string &p_value, const std::string &p_trim_chars = " \t"); - - /*! - * \brief Convert the provided string into a list of arguments - * \param[in] p_value The string value - * \param[in] p_separator The separator sequence to use for the spliting process - * \return The item list - * \code{.cc} - * std::string str = "This is a test for spliting a string with a white spave"; - * std::vector tokens = converter::get_instance().split(str, " "); - * std::clog << "Tokens: " << std::endl; - * for (auto it = tokens.begin(); it != tokens.end(); ++it) { - * std::clog << " " << *it << std::endl; - * } - * \endcode - */ - std::vector split(const std::string &p_value, const std::string &p_separator); - - /*! - * \brief Convert the provided string into a list of arguments - * \param[in] p_value The string value - * \return The arguments list - * \code{.cc} - * std::string str = "--host localhost --port 12345 --duration -1"; - * std::vector tokens = converter::get_instance().split_arguments_line(str); - * std::clog << "Tokens: " << std::endl; - * for (auto it = tokens.begin(); it != tokens.end(); ++it) { - * std::clog << " " << *it << std::endl; - * } - * \endcode - */ - std::vector split_arguments_line(const std::string &p_value); - - /*! - * \brief Convert the provided buffer into a Base64 - * \param[in] p_value The buffer value - * \return The Base64 encoded buffert - */ - std::vector buffer_to_base64(const std::vector &p_value); - - /*! - * \brief Convert the provided Base64 buffer - * \param[in] p_value The buffer value - * \return The Base64 encoded buffert - */ - std::vector base64_to_buffer(const std::vector &p_value); - - static const std::string lut_u; - static const std::string lut_l; - static const std::string base64_enc_map; - -}; // End of class converter +/*! + * \file converter.hh + * \brief Helper class for types converter. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include + +#include +#include +#include + +#include +#include // LONG_MAX, LLONG_MAX +#include +#include // time_t, struct tm, difftime, time, mktime + +/*! + * \class converter + * \brief This class provide a set of methods for types conversions + * \remark Singleton pattern + */ +class converter { + + /*! + * \brief Unique static object reference of this class + */ + static converter *instance; + + /*! + * \brief Default private ctor + */ + converter(){}; + /*! + * \brief Default private dtor + */ + ~converter() { + if (instance != NULL) { + delete instance; + instance = NULL; + } + }; + +public: /*! \publicsection */ + /*! + * \brief Public accessor to the single object reference + */ + inline static converter &get_instance() { + if (instance == NULL) + instance = new converter(); + return *instance; + }; + +public: + /*! + * \enum endian_t + * \brief Endianess style + */ + typedef enum { big_endian, little_endian } endian_t; + +public: + /*! + * \brief Convert a Binary Coded Decimal value into a binary value + * \param[in] p_value The BDC value + * \return The binary value + * \inline + */ + inline uint8_t bcd_to_bin(const uint8_t p_value) { return ((p_value / 16 * 10) + (p_value % 16)); }; + + /*! + * \brief Convert a binary value into a Binary Coded Decimal value + * \param[in] p_value The binary value + * \return The BCD value + * \inline + */ + inline uint8_t bin_to_bcd(const uint8_t p_value) { return ((p_value / 10 * 16) + (p_value % 10)); }; + + /*! + * \brief Swap two bytes length value (e.g. 0xCAFE becomes 0xFECA) + * \param[in] p_value The value to swap + * \return The swapped value + * \inline + */ + uint16_t swap(const uint16_t p_value); + inline int16_t swap(const int16_t p_value) { return static_cast(swap(static_cast(p_value))); }; + /*! + * \brief Swap four bytes length value (used for littel endian / big endian) + * \param[in] p_value The value to swap + * \return The swapped value + */ + uint32_t swap(const uint32_t p_value); + inline int32_t swap(const int32_t p_value) { return static_cast(swap(static_cast(p_value))); }; + + /*! + * \brief Convert a string into an hexadecimal string + * \param[in] p_value The string value + * \return The hexadecimal value + */ + std::string string_to_hexa(const std::string &p_value, const bool p_uppercase = false); + /*! + * \brief Convert a bytes array int32_t an hexadecimal string + * \param[in] p_value The bytes array value + * \return The hexadecimal value + */ + std::string bytes_to_hexa(const std::vector &p_value, const bool p_uppercase = false); + /*! + * \brief Convert an hexadecimal string into a bytes array + * \param[in] p_value The hexadecimal value + * \return The bytes array value + */ + std::vector hexa_to_bytes(const std::string &p_value); + + /*! + * \brief Convert a time in time_t format into a string formated according to RFC 822, 1036, 1123, 2822 + * \param[in] p_time The time to convert in time_t format + * \return The time string formated + * \see http://www.unixtimestamp.com/ + * @code + * std::string result = time_to_string(1489755780); + * result.compare("Fri, 17 Mar 2017 13:03:00 +0000") == 0 // When time zone is set to UTC + * @endcode + * \remark Use commands 1) timedatectl to change your machine timezone (e.g. sudo timedatectl set-timezone UTC to change machine timezone to UTC, 2) + * timedatectl list-timezones to get the list of the timezones) + */ + std::string time_to_string(const time_t p_time); + /*! + * \brief Convert a time in struct tm format into a string formated according to RFC 822, 1036, 1123, 2822 + * \param[in] p_time The time to convert in struct tm format + * \return The time string formated + * \see http://www.unixtimestamp.com/ + */ + std::string time_to_string(const struct tm &p_time); + + /*! + * \brief Convert a 16-bits integer (int16_t) into a bytes array + * \param[in] p_value The 16-bits integer value + * \param[in] p_endianess Endianess style. Default: big_endian + * \return The bytes array value + */ + inline std::vector short_to_bytes(const int16_t p_value, const endian_t p_endianess = big_endian) const { + std::vector result(sizeof(short), 0x00); + for (int i = sizeof(short) - 1; i >= 0; i--) { + int offset = (sizeof(short) - 1 - i) * 8; + result[i] = static_cast((p_value >> offset) & 0xFF); + } // End of 'for' statement + return result; + }; // End of short_to_bytes + + /*! + * \brief Convert a bytes array into a 16-bits integer (int16_t) + * \param[in] p_value The bytes array + * \param[in] p_endianess Endianess style. Default: big_endian + * \return The 16-bits integer on success, SHRT_MAX on error (wrong bytes array size) + */ + inline int16_t bytes_to_short(const std::vector &p_value, const endian_t p_endianess = big_endian) const { + // Sanity check + if (p_value.size() > sizeof(short)) { + return SHRT_MAX; + } + int16_t value = 0; + for (size_t i = 0; i < p_value.size(); i++) { + value = (value << 8) + (p_value[i] & 0xff); + } // End of 'for' statement + return value; + }; // End of bytes_to_short + + /*! + * \brief Convert a 32-bits integer (int32_t) into a bytes array + * \param[in] p_value The 32-bits integer value + * \param[in] p_endianess Endianess style. Default: big_endian + * \return The bytes array value + */ + inline std::vector int_to_bytes(const int32_t p_value, const endian_t p_endianess = big_endian) const { + /*uint8_t bytes[sizeof(p_value)]; + std::copy( + static_cast(static_cast(&p_value)), + static_cast(static_cast(&p_value)) + sizeof(p_value), + bytes + ); + std::vector result(bytes, bytes + sizeof(bytes) / sizeof(uint8_t));*/ + std::vector result(sizeof(int), 0x00); + for (int i = sizeof(int) - 1; i >= 0; i--) { + int offset = (sizeof(int) - 1 - i) * 8; + result[i] = static_cast((p_value >> offset) & 0xFF); + } // End of 'for' statement + return result; + }; // End of int_to_bytes + + /*! + * \brief Convert a bytes array into a 32-bits integer (int32_t) + * \param[in] p_value The bytes array + * \param[in] p_endianess Endianess style. Default: big_endian + * \return The 32-bits integer on success, LONG_MAX on error (wrong bytes array size) + */ + inline int32_t bytes_to_int(const std::vector &p_value, const endian_t p_endianess = big_endian) const { + // Sanity check + if (p_value.size() > sizeof(int)) { + return INT_MAX; + } + int32_t value = 0; + for (size_t i = 0; i < p_value.size(); i++) { + value = (value << 8) + (p_value[i] & 0xff); + } // End of 'for' statement + return value; + // return *((int *)(&p_value[0])); + }; // End of bytes_to_int + + /*! + * \brief Convert a 64-bits integer (int64_t) into a bytes array + * \param[in] p_value The 64-bits integer value + * \param[in] p_endianess Endianess style. Default: big_endian + * \return The bytes array value + */ + inline std::vector long_to_bytes(const int64_t p_value, const endian_t p_endianess = big_endian) const { + /*uint8_t bytes[sizeof(p_value)]; + std::copy( + static_cast(static_cast(&p_value)), + static_cast(static_cast(&p_value)) + sizeof(p_value), + bytes + ); + std::vector result(bytes, bytes + sizeof(bytes) / sizeof(uint8_t));*/ + std::vector result(sizeof(int64_t), 0x00); + for (int i = sizeof(int64_t) - 1; i >= 0; i--) { + int offset = (sizeof(int64_t) - 1 - i) * 8; + result[i] = static_cast((p_value >> offset) & 0xFF); + } // End of 'for' statement + return result; + }; // End of long_to_bytes + + /*! + * \brief Convert a bytes array into a 64-bits integer (int64_t) + * \param[in] p_value The bytes array + * \param[in] p_endianess Endianess style. Default: big_endian + * \return The 64-bits integer on success, LLONG_MAX on error (wrong bytes array size) + */ + inline int64_t bytes_to_long(const std::vector &p_value, const endian_t p_endianess = big_endian) const { + // Sanity check + if (p_value.size() > sizeof(int64_t)) { + return LLONG_MAX; + } + int64_t value = 0; + for (size_t i = 0; i < p_value.size(); i++) { + value = (value << 8) + (p_value[i] & 0xff); + } // End of 'for' statement + return value; + // return *((long *)(&p_value[0])); + }; // End of bytes_to_long + + /*! + * \brief Convert a float value into a bytes array + * \param[in] p_value The float value + * \return The bytes array value + */ + inline std::vector float_to_bytes(const float p_value) const { + uint8_t bytes[sizeof(p_value)]; + std::copy(static_cast(static_cast(&p_value)), + static_cast(static_cast(&p_value)) + sizeof(p_value), bytes); + std::vector result(bytes, bytes + sizeof(bytes) / sizeof(uint8_t)); + return result; + }; // End of float_to_long + + /*! + * \brief Convert a bytes array into a float + * \param[in] p_value The bytes array + * \return The float value + */ + inline float bytes_to_float(const std::vector &p_value) const { return *((float *)(&p_value[0])); }; // End of bytes_to_float + + /*! + * \brief Convert a string into a bytes array + * \param[in] p_value The string value + * \return The bytes array value + */ + inline std::vector string_to_bytes(const std::string &p_value) const { + return std::vector(p_value.begin(), p_value.end()); + }; // End of string_to_bytes + + /*! + * \brief Convert a bytes array into a string + * \param[in] p_value The bytes array value + * \return The string value + */ + inline std::string bytes_to_string(const std::vector &p_value) const { + return std::string(p_value.begin(), p_value.end()); + }; // End of bytes_to_string + +public: + /*! + * \brief Convert a string into an integer + * \param[in] p_value The string value + * \return The integer value + */ + inline int32_t string_to_int(const std::string &p_value) const { + return std::stoi(p_value); + // return atoi(p_value.c_str()); + }; // End of string_to_int + + /*! + * \brief Convert an integer into a string + * \param[in] p_value The integer value + * \return The string value + */ + inline std::string int_to_string(const int32_t &p_value) const { + std::ostringstream ss; + ss << p_value; + return ss.str(); + }; // End of string_to_bytes + + /*! + * \brief Convert a string in to lower case + * \param[in/out] p_value The string value to convert + */ + inline void to_lower(std::string &p_value) { std::transform(p_value.begin(), p_value.end(), p_value.begin(), ::tolower); } + + /*! + * \brief Convert a string in to upper case + * \param[in/out] p_value The string value to convert + */ + inline void to_upper(std::string &p_value) { std::transform(p_value.begin(), p_value.end(), p_value.begin(), ::toupper); } + +public: + /*! + * \brief Returns a copy of the string, with leading and trailing special characters omitted + * \param[in] p_value The string value + * \param[in] p_trim_chars The special characters to be omitted. Default: ' ' and TAB + * \return The new string value + */ + std::string trim(const std::string &p_value, const std::string &p_trim_chars = " \t"); + + /*! + * \brief Convert the provided string into a list of arguments + * \param[in] p_value The string value + * \param[in] p_separator The separator sequence to use for the spliting process + * \return The item list + * \code{.cc} + * std::string str = "This is a test for spliting a string with a white spave"; + * std::vector tokens = converter::get_instance().split(str, " "); + * std::clog << "Tokens: " << std::endl; + * for (auto it = tokens.begin(); it != tokens.end(); ++it) { + * std::clog << " " << *it << std::endl; + * } + * \endcode + */ + std::vector split(const std::string &p_value, const std::string &p_separator); + + /*! + * \brief Convert the provided string into a list of arguments + * \param[in] p_value The string value + * \return The arguments list + * \code{.cc} + * std::string str = "--host localhost --port 12345 --duration -1"; + * std::vector tokens = converter::get_instance().split_arguments_line(str); + * std::clog << "Tokens: " << std::endl; + * for (auto it = tokens.begin(); it != tokens.end(); ++it) { + * std::clog << " " << *it << std::endl; + * } + * \endcode + */ + std::vector split_arguments_line(const std::string &p_value); + + /*! + * \brief Convert the provided buffer into a Base64 + * \param[in] p_value The buffer value + * \return The Base64 encoded buffert + */ + std::vector buffer_to_base64(const std::vector &p_value); + + /*! + * \brief Convert the provided Base64 buffer + * \param[in] p_value The buffer value + * \return The Base64 encoded buffert + */ + std::vector base64_to_buffer(const std::vector &p_value); + + static const std::string lut_u; + static const std::string lut_l; + static const std::string base64_enc_map; + +}; // End of class converter diff --git a/ccsrc/Framework/include/layer.hh b/ccsrc/Framework/include/layer.hh index d964e4d2bb9dc262da1eb4ce577689ada2150362..52f171ccacb4b5ec20222181e9a5449c42d99776 100644 --- a/ccsrc/Framework/include/layer.hh +++ b/ccsrc/Framework/include/layer.hh @@ -1,143 +1,143 @@ -/*! - * \file layer.hh - * \brief Header file for ITS abstract protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -#include "params.hh" - -class OCTETSTRING; //! Forward declaration of TITAN class -class BITSTRING; //! Forward declaration of TITAN class -class CHARSTRING; //! Forward declaration of TITAN class -class INTEGER; //! Forward declaration of TITAN class - -/*! - * \class layer - * \brief This class provides basic description of an ITS protocol layer - */ -class layer { - std::vector upperLayers; //! List of the upper protocol layers - std::vector lowerLayers; //! List of the lower protocol layers - -protected: - std::string type; //! Type description, it indicates the protocol type (e.g. CAM, DENM, GN, ETH, PCAP...) - -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the layer class - */ - explicit layer() : upperLayers(), lowerLayers(), type(std::string("")){}; - - /*! - * \brief Specialized constructor - * Create a new instance of the layer class with its type description - * \param[in] p_type The port type name (e.g. GN for the GeoNetworking layer) - * \remark This constructor is called by the layer factory - * \see layer_factory - */ - explicit layer(const std::string &p_type) : upperLayers(), lowerLayers(), type(std::string(p_type.begin(), p_type.end())){}; - - /*! - * \brief Default destructor - * \todo Remove logs - */ - virtual ~layer() { - // Double linked list, only remove layers in lowerLayers from the lowest one - std::for_each(lowerLayers.rbegin(), lowerLayers.rend(), [](layer *it) { delete it; }); - lowerLayers.clear(); - upperLayers.clear(); - }; - - /*! - * \fn void delete_layer(); - * \brief Delete this layer - * \todo To be implemented - */ - void delete_layer(){}; - -public: //! \publicsection - /*! - * \inline - * \fn void add_upper_layer(layer* p_layer); - * \brief Add a new layer in the list of the upper layer - * \param[in] p_layer The layer protocol to be removed - */ - inline void add_upper_layer(layer *p_layer) { - if (p_layer != NULL) { - upperLayers.push_back(p_layer); - p_layer->lowerLayers.push_back(this); - }; - }; - - /*! - * \fn void remove_upper_layer(layer* p_layer); - * \brief Remove the specified upper layer protocol from the list of the upper layer - * \param[in] p_layer The layer protocol to be removed - * \todo To be implemented - */ - void remove_upper_layer(layer *p_layer){}; - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - * \todo Remove the logs - * \virtual - */ - virtual void send_data(OCTETSTRING &p_data, params &p_params){}; - - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - * \todo Remove the logs - * \virtual - */ - virtual void receive_data(OCTETSTRING &p_data, params &p_params) {} - - /*! - * \inline - * \fn const std::string& to_string(); - * \brief Remove the specified upper layer protocol from the list of the upper layer - * \param[in] The layer protocol to be removed - */ - inline const std::string &to_string() const { return type; }; - -protected: //! \protectedsection - inline void to_all_layers(std::vector &layers, OCTETSTRING &data, params ¶ms) { - for (std::vector::const_iterator it = layers.cbegin(); it != layers.cend(); ++it) { - layer *p = *it; - p->receive_data(data, params); // FIXME BUG I - } // End of 'for' statement - }; - - inline void receive_to_all_layers(OCTETSTRING &data, params ¶ms) { - for (std::vector::const_iterator it = upperLayers.cbegin(); it != upperLayers.cend(); ++it) { - layer *p = *it; - p->receive_data(data, params); - } // End of 'for' statement - }; - - inline void send_to_all_layers(OCTETSTRING &data, params ¶ms) { - for (std::vector::const_iterator it = lowerLayers.cbegin(); it != lowerLayers.cend(); ++it) { - layer *p = *it; - p->send_data(data, params); - } // End of 'for' statement - }; -}; // End of class layer +/*! + * \file layer.hh + * \brief Header file for ITS abstract protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +#include "params.hh" + +class OCTETSTRING; //! Forward declaration of TITAN class +class BITSTRING; //! Forward declaration of TITAN class +class CHARSTRING; //! Forward declaration of TITAN class +class INTEGER; //! Forward declaration of TITAN class + +/*! + * \class layer + * \brief This class provides basic description of an ITS protocol layer + */ +class layer { + std::vector upperLayers; //! List of the upper protocol layers + std::vector lowerLayers; //! List of the lower protocol layers + +protected: + std::string type; //! Type description, it indicates the protocol type (e.g. CAM, DENM, GN, ETH, PCAP...) + +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the layer class + */ + explicit layer() : upperLayers(), lowerLayers(), type(std::string("")){}; + + /*! + * \brief Specialized constructor + * Create a new instance of the layer class with its type description + * \param[in] p_type The port type name (e.g. GN for the GeoNetworking layer) + * \remark This constructor is called by the layer factory + * \see layer_factory + */ + explicit layer(const std::string &p_type) : upperLayers(), lowerLayers(), type(std::string(p_type.begin(), p_type.end())){}; + + /*! + * \brief Default destructor + * \todo Remove logs + */ + virtual ~layer() { + // Double linked list, only remove layers in lowerLayers from the lowest one + std::for_each(lowerLayers.rbegin(), lowerLayers.rend(), [](layer *it) { delete it; }); + lowerLayers.clear(); + upperLayers.clear(); + }; + + /*! + * \fn void delete_layer(); + * \brief Delete this layer + * \todo To be implemented + */ + void delete_layer(){}; + +public: //! \publicsection + /*! + * \inline + * \fn void add_upper_layer(layer* p_layer); + * \brief Add a new layer in the list of the upper layer + * \param[in] p_layer The layer protocol to be removed + */ + inline void add_upper_layer(layer *p_layer) { + if (p_layer != NULL) { + upperLayers.push_back(p_layer); + p_layer->lowerLayers.push_back(this); + }; + }; + + /*! + * \fn void remove_upper_layer(layer* p_layer); + * \brief Remove the specified upper layer protocol from the list of the upper layer + * \param[in] p_layer The layer protocol to be removed + * \todo To be implemented + */ + void remove_upper_layer(layer *p_layer){}; + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + * \todo Remove the logs + * \virtual + */ + virtual void send_data(OCTETSTRING &p_data, params &p_params){}; + + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + * \todo Remove the logs + * \virtual + */ + virtual void receive_data(OCTETSTRING &p_data, params &p_params) {} + + /*! + * \inline + * \fn const std::string& to_string(); + * \brief Remove the specified upper layer protocol from the list of the upper layer + * \param[in] The layer protocol to be removed + */ + inline const std::string &to_string() const { return type; }; + +protected: //! \protectedsection + inline void to_all_layers(std::vector &layers, OCTETSTRING &data, params ¶ms) { + for (std::vector::const_iterator it = layers.cbegin(); it != layers.cend(); ++it) { + layer *p = *it; + p->receive_data(data, params); // FIXME BUG I + } // End of 'for' statement + }; + + inline void receive_to_all_layers(OCTETSTRING &data, params ¶ms) { + for (std::vector::const_iterator it = upperLayers.cbegin(); it != upperLayers.cend(); ++it) { + layer *p = *it; + p->receive_data(data, params); + } // End of 'for' statement + }; + + inline void send_to_all_layers(OCTETSTRING &data, params ¶ms) { + for (std::vector::const_iterator it = lowerLayers.cbegin(); it != lowerLayers.cend(); ++it) { + layer *p = *it; + p->send_data(data, params); + } // End of 'for' statement + }; +}; // End of class layer diff --git a/ccsrc/Framework/include/layer_factory.hh b/ccsrc/Framework/include/layer_factory.hh index 3173153dff338c1923f32dd1569c06501ffc5361..7b8ac35a611565cef89956c2a142bfe3b0576604 100644 --- a/ccsrc/Framework/include/layer_factory.hh +++ b/ccsrc/Framework/include/layer_factory.hh @@ -1,121 +1,121 @@ -/*! - * \file layer_factory.hh - * \brief Header file for ITS abstract protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -#include "layer.hh" - -/*! - * \class layer_factory - * \brief This class provides a factory class to create layer class instances - * \abstract - */ -class layer_factory { -public: //! \publicsection - /*! - * \fn codec(); - * \brief Default constructor - */ - layer_factory(){}; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description (cf. remark) - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \remark The description below introduces layers stack in case of ITS project: - * CAM layer - * next_header : btpA|btpB (overwrite BTP.type) - * header_type : tsb|gbc - * header_sub_type : sh (single hop) - * DENM layer - * next_header : btpA|btpB (overwrite BTP.type) - * header_type : tsb|gbc - * BTP layer - * type : btpA|btpB - * destination port: dst_port - * source port : src_port - * device_mode : Set to 1 if the layer shall encapsulate upper layer PDU - * GN layer - * its_aid : ITS AID as defined by ETSI TS 102 965 V1.2.1. Default: 141 - * ll_address : GeoNetworking address of the Test System - * latitude : latitude of the Test System - * longitude : longitude of the Test System - * beaconing : Set to 1 if GnLayer shall start beaconing - * Beaconing timer expiry : expiry (ms) - * device_mode : Set to 1 if the layer shall encapsulate upper layer PDU - * secured_mode : Set to 1 if message exchanges shall be signed - * encrypted_mode : Set to 1 if message exchanges shall be encrypted - * NOTE: For signed & encrypted message exchanges, both secured_mode and encrypted_mode shall be set to 1 - * certificate : Certificate identifier the Test Adapter shall use - * secure_db_path : Path to the certificates and keys storage location - * hash : Hash algorithm to be used when secured mode is set - * Authorized values are SHA-256 or SHA-384 - * Default: SHA-256 - * signature : Signature algorithm to be used when secured mode is set - * Authorized values are NISTP-256, BP-256 and BP-384 - * Default: NISTP-256 - * cypher : Cyphering algorithm to be used when secured mode is set - * Ethernet layer - * mac_src :Source MAC address - * mac_bc :Broadcast address - * eth_type : Ethernet type - * Commsignia layer - * mac_src : Device MAC address, used to discard packets - * To indicate no filering, use the value 000000000000 - * mac_bc : Broadcast address - * eth_type : Ethernet type, used to discard packets - * target_host : Device address - * target_port : Device port - * source_port : Test System port - * interface_id: Interface id, used to discard packets - * tx_power : TX power (dB) - * UDP layer (IP/UDP based on Pcap) - * dst_ip : destination IPv4 address (aa.bb.cc.dd) - * dst_port: destination port - * src_ip : source IPv4 address (aa.bb.cc.dd) - * src_port: source port - * Pcap layer - * mac_src : Source MAC address, used to exclude from capture the acket sent by the Test System - * filter : Pcap filter (compliant with tcpdump syntax) - * E.g. filter=and ether src 04e548000001 - * Online mode: - * nic: Local NIC - * If set, online mode is used - * Offline mode (nic is present but not set): - * file : File to read - * frame_offset: Frame offset, used to skip packets with frame number < frame_offset - * time_offset : Time offset, used to skip packets with time offset < time_offset - * save_mode : 1 to save sent packet, 0 otherwise - * Here are some examples: - * GeoNetworking multiple component case: - * NodeB.geoNetworkingPort.params := -"GN(ll_address=04e548000001,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/COMMSIGNIA(mac_src=04e548000001,mac_bc=FFFFFFFFFFFF,eth_type=8947,target_host=10.200.1.101,target_port=7942,source_port=7943,its_aid=141,interface_id=2,tx_power=-32)/UDP(dst_ip=192.168.56.1,dst_port=12346,src_ip=192.168.156.4,src_port=12345)/ETH(mac_src=04e548000001,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=04e548000001,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01_short.pcap,filter=and -(udp port 30000 or udp port 7943))" NodeC.geoNetworkingPort.params := -"GN(ll_address=70b3d5791b48,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/COMMSIGNIA(mac_src=70b3d5791b48,mac_bc=FFFFFFFFFFFF,eth_type=8947,target_host=10.200.1.101,target_port=7942,source_port=7943,its_aid=141,interface_id=2,tx_power=-32)/UDP(dst_ip=192.168.56.1,dst_port=12346,src_ip=192.168.156.4,src_port=12345)/ETH(mac_src=70b3d5791b48,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=70b3d5791b48,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01_short.pcap,filter=and -(udp port 30000 or udp port 7943))" - * NodeB.geoNetworkingPort.params := -"GN(ll_address=04e548000001,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/ETH(mac_src=04e548000001,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=04e548000001,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01.pcap,filter=and -ether src 04e548000001)" #NodeC.geoNetworkingPort.params := -"GN(ll_address=70b3d5791b48,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/ETH(mac_src=70b3d5791b48,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=70b3d5791b48,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01.pcap,filter=and -ether src 70b3d5791b48)" - * UpperTester port based on UDP - * system.utPort.params := -"UT_GN/UDP(dst_ip=192.168.1.1,dst_port=12346,src_ip=192.168.156.4,src_port=12345)/ETH(mac_src=026f8338c1e5,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=0800275c4959,nic=enp0s8,filter=and -udp port 12346)" - * \pure - */ - virtual layer *create_layer(const std::string &p_type, const std::string &p_params) = 0; -}; // End of class layer_factory +/*! + * \file layer_factory.hh + * \brief Header file for ITS abstract protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +#include "layer.hh" + +/*! + * \class layer_factory + * \brief This class provides a factory class to create layer class instances + * \abstract + */ +class layer_factory { +public: //! \publicsection + /*! + * \fn codec(); + * \brief Default constructor + */ + layer_factory(){}; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description (cf. remark) + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \remark The description below introduces layers stack in case of ITS project: + * CAM layer + * next_header : btpA|btpB (overwrite BTP.type) + * header_type : tsb|gbc + * header_sub_type : sh (single hop) + * DENM layer + * next_header : btpA|btpB (overwrite BTP.type) + * header_type : tsb|gbc + * BTP layer + * type : btpA|btpB + * destination port: dst_port + * source port : src_port + * device_mode : Set to 1 if the layer shall encapsulate upper layer PDU + * GN layer + * its_aid : ITS AID as defined by ETSI TS 102 965 V1.2.1. Default: 141 + * ll_address : GeoNetworking address of the Test System + * latitude : latitude of the Test System + * longitude : longitude of the Test System + * beaconing : Set to 1 if GnLayer shall start beaconing + * Beaconing timer expiry : expiry (ms) + * device_mode : Set to 1 if the layer shall encapsulate upper layer PDU + * secured_mode : Set to 1 if message exchanges shall be signed + * encrypted_mode : Set to 1 if message exchanges shall be encrypted + * NOTE: For signed & encrypted message exchanges, both secured_mode and encrypted_mode shall be set to 1 + * certificate : Certificate identifier the Test Adapter shall use + * secure_db_path : Path to the certificates and keys storage location + * hash : Hash algorithm to be used when secured mode is set + * Authorized values are SHA-256 or SHA-384 + * Default: SHA-256 + * signature : Signature algorithm to be used when secured mode is set + * Authorized values are NISTP-256, BP-256 and BP-384 + * Default: NISTP-256 + * cypher : Cyphering algorithm to be used when secured mode is set + * Ethernet layer + * mac_src :Source MAC address + * mac_bc :Broadcast address + * eth_type : Ethernet type + * Commsignia layer + * mac_src : Device MAC address, used to discard packets + * To indicate no filering, use the value 000000000000 + * mac_bc : Broadcast address + * eth_type : Ethernet type, used to discard packets + * target_host : Device address + * target_port : Device port + * source_port : Test System port + * interface_id: Interface id, used to discard packets + * tx_power : TX power (dB) + * UDP layer (IP/UDP based on Pcap) + * dst_ip : destination IPv4 address (aa.bb.cc.dd) + * dst_port: destination port + * src_ip : source IPv4 address (aa.bb.cc.dd) + * src_port: source port + * Pcap layer + * mac_src : Source MAC address, used to exclude from capture the acket sent by the Test System + * filter : Pcap filter (compliant with tcpdump syntax) + * E.g. filter=and ether src 04e548000001 + * Online mode: + * nic: Local NIC + * If set, online mode is used + * Offline mode (nic is present but not set): + * file : File to read + * frame_offset: Frame offset, used to skip packets with frame number < frame_offset + * time_offset : Time offset, used to skip packets with time offset < time_offset + * save_mode : 1 to save sent packet, 0 otherwise + * Here are some examples: + * GeoNetworking multiple component case: + * NodeB.geoNetworkingPort.params := +"GN(ll_address=04e548000001,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/COMMSIGNIA(mac_src=04e548000001,mac_bc=FFFFFFFFFFFF,eth_type=8947,target_host=10.200.1.101,target_port=7942,source_port=7943,its_aid=141,interface_id=2,tx_power=-32)/UDP(dst_ip=192.168.56.1,dst_port=12346,src_ip=192.168.156.4,src_port=12345)/ETH(mac_src=04e548000001,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=04e548000001,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01_short.pcap,filter=and +(udp port 30000 or udp port 7943))" NodeC.geoNetworkingPort.params := +"GN(ll_address=70b3d5791b48,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/COMMSIGNIA(mac_src=70b3d5791b48,mac_bc=FFFFFFFFFFFF,eth_type=8947,target_host=10.200.1.101,target_port=7942,source_port=7943,its_aid=141,interface_id=2,tx_power=-32)/UDP(dst_ip=192.168.56.1,dst_port=12346,src_ip=192.168.156.4,src_port=12345)/ETH(mac_src=70b3d5791b48,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=70b3d5791b48,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01_short.pcap,filter=and +(udp port 30000 or udp port 7943))" + * NodeB.geoNetworkingPort.params := +"GN(ll_address=04e548000001,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/ETH(mac_src=04e548000001,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=04e548000001,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01.pcap,filter=and +ether src 04e548000001)" #NodeC.geoNetworkingPort.params := +"GN(ll_address=70b3d5791b48,latitude=43551050,longitude=10298730,beaconing=0,expiry=1000,its_aid=141)/ETH(mac_src=70b3d5791b48,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=70b3d5791b48,file=/home/vagrant/TriesAndDelete/etsi_its/testdata/TC_AUTO_IOT_DENM_RWW_BV_01.pcap,filter=and +ether src 70b3d5791b48)" + * UpperTester port based on UDP + * system.utPort.params := +"UT_GN/UDP(dst_ip=192.168.1.1,dst_port=12346,src_ip=192.168.156.4,src_port=12345)/ETH(mac_src=026f8338c1e5,mac_dst=0A0027000011,eth_type=0800)/PCAP(mac_src=0800275c4959,nic=enp0s8,filter=and +udp port 12346)" + * \pure + */ + virtual layer *create_layer(const std::string &p_type, const std::string &p_params) = 0; +}; // End of class layer_factory diff --git a/ccsrc/Framework/include/layer_stack_builder.hh b/ccsrc/Framework/include/layer_stack_builder.hh index d0fa3f48c2599f49cde25ad5dc71b1f425fb576c..2d1b25a59eac4e0dfeb395256945a4659b5535f6 100644 --- a/ccsrc/Framework/include/layer_stack_builder.hh +++ b/ccsrc/Framework/include/layer_stack_builder.hh @@ -1,66 +1,66 @@ -/*! - * \file layer_stack_builder.hh - * \brief Header file for ITS protocol stack builder. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_factory.hh" - -/*! - * \class layer_stack_builder - * \brief This class provides a factory class to create Layer class instances - */ -class layer_stack_builder { -private: //! \privatesection - typedef std::map LayerFactoryMap; - - static layer_stack_builder * _instance; //! Smart pointer to the unique instance of the logger framework - std::map _layer_factories; //! The list of the registered \see t_layer factories - - /*! - * \brief Default constructor - * Create a new instance of the layer_stack_builder class - * \private - */ - layer_stack_builder(); // can not be created manually -public: //! \publicsection - /*! - * \fn layer_stack_builder* get_instance(); - * \brief Accessor for the unique instance of the logger framework - * \static - */ - static layer_stack_builder *get_instance(); - - /*! - * \fn void register_layer_factory(const std::string & p_type, layer_factory* p_layer_factory); - * \brief Add a new layer factory - * \param[in] p_type The layer identifier (e.g. GN for the GeoNetworking layer...) - * \param[in] p_layer_factory A reference to the \see layer_factory - * \static - */ - static void register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory); - -private: //! \privatesection - /*! - * \fn void _register_layer_factory(const std::string & p_type, layer_factory* p_layer_factory); - * \brief Add a new layer factory - * \param[in] p_type The layer identifier (e.g. GN for the GeoNetworking layer...) - * \param[in] p_layer_factory A reference to the \see layer_factory - */ - void _register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory); - -public: //! \publicsection - /*! - * \fn layer* create_layer_stack(const char* p_layer_stack_description); - * \brief Add a new layer factory - * \param[in] p_layer_stack_description A textual description of the layer to create - * \return The created layer object on success, nullptr otherwise - */ - layer *create_layer_stack(const char *p_layer_stack_description); -}; // End of class layer_stack_builder +/*! + * \file layer_stack_builder.hh + * \brief Header file for ITS protocol stack builder. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_factory.hh" + +/*! + * \class layer_stack_builder + * \brief This class provides a factory class to create Layer class instances + */ +class layer_stack_builder { +private: //! \privatesection + typedef std::map LayerFactoryMap; + + static layer_stack_builder * _instance; //! Smart pointer to the unique instance of the logger framework + std::map _layer_factories; //! The list of the registered \see t_layer factories + + /*! + * \brief Default constructor + * Create a new instance of the layer_stack_builder class + * \private + */ + layer_stack_builder(); // can not be created manually +public: //! \publicsection + /*! + * \fn layer_stack_builder* get_instance(); + * \brief Accessor for the unique instance of the logger framework + * \static + */ + static layer_stack_builder *get_instance(); + + /*! + * \fn void register_layer_factory(const std::string & p_type, layer_factory* p_layer_factory); + * \brief Add a new layer factory + * \param[in] p_type The layer identifier (e.g. GN for the GeoNetworking layer...) + * \param[in] p_layer_factory A reference to the \see layer_factory + * \static + */ + static void register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory); + +private: //! \privatesection + /*! + * \fn void _register_layer_factory(const std::string & p_type, layer_factory* p_layer_factory); + * \brief Add a new layer factory + * \param[in] p_type The layer identifier (e.g. GN for the GeoNetworking layer...) + * \param[in] p_layer_factory A reference to the \see layer_factory + */ + void _register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory); + +public: //! \publicsection + /*! + * \fn layer* create_layer_stack(const char* p_layer_stack_description); + * \brief Add a new layer factory + * \param[in] p_layer_stack_description A textual description of the layer to create + * \return The created layer object on success, nullptr otherwise + */ + layer *create_layer_stack(const char *p_layer_stack_description); +}; // End of class layer_stack_builder diff --git a/ccsrc/Framework/include/oer_codec.hh b/ccsrc/Framework/include/oer_codec.hh index 45b1e3127eb4ba2212e5f403fd4bb514c5e06ab0..51a32cd1c5ec5cb62d86d67d3a84d6f2b0389045 100644 --- a/ccsrc/Framework/include/oer_codec.hh +++ b/ccsrc/Framework/include/oer_codec.hh @@ -1,48 +1,48 @@ -#pragma once - -#include "params.hh" - -class OCTETSTRING; -class CHARSTRING; -class BITSTRING; - -struct asn_TYPE_descriptor_s; -class asn1_recode_oer { -protected: - int xer2oer(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); - int oer2xer(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); - int recode(const asn_TYPE_descriptor_s &td, int from, int to, TTCN_Buffer &buf); -}; - -template class oer_codec : public asn1_recode_oer { -public: - virtual int encode(const TPDU &msg, BITSTRING &bits) = 0; - virtual int decode(const BITSTRING &bits, TPDU &msg) = 0; - -protected: - inline int _decode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const BITSTRING &p_data, TPDU &msg) { - TTCN_Buffer buf(bit2oct(p_data)); - TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); - int rc = oer2xer(td, buf); - if (rc > 0) { - msg.decode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ACCEPT_ALL); - rc = buf.get_len(); - } - return rc; - } - inline int _encode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const TPDU &msg, BITSTRING &p_data) { - int rc = -1; - TTCN_Buffer buf; - TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); - msg.encode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ENCODE_DER); - if (buf.get_len() > 0) { - rc = xer2oer(td, buf); - if (rc > 0) { - p_data = oct2bit(OCTETSTRING(buf.get_len(), buf.get_data())); - } - } - return rc; - } -}; - -#endif +#pragma once + +#include "params.hh" + +class OCTETSTRING; +class CHARSTRING; +class BITSTRING; + +struct asn_TYPE_descriptor_s; +class asn1_recode_oer { +protected: + int xer2oer(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); + int oer2xer(const asn_TYPE_descriptor_s &td, TTCN_Buffer &buf); + int recode(const asn_TYPE_descriptor_s &td, int from, int to, TTCN_Buffer &buf); +}; + +template class oer_codec : public asn1_recode_oer { +public: + virtual int encode(const TPDU &msg, BITSTRING &bits) = 0; + virtual int decode(const BITSTRING &bits, TPDU &msg) = 0; + +protected: + inline int _decode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const BITSTRING &p_data, TPDU &msg) { + TTCN_Buffer buf(bit2oct(p_data)); + TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); + int rc = oer2xer(td, buf); + if (rc > 0) { + msg.decode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ACCEPT_ALL); + rc = buf.get_len(); + } + return rc; + } + inline int _encode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const TPDU &msg, BITSTRING &p_data) { + int rc = -1; + TTCN_Buffer buf; + TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); + msg.encode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ENCODE_DER); + if (buf.get_len() > 0) { + rc = xer2oer(td, buf); + if (rc > 0) { + p_data = oct2bit(OCTETSTRING(buf.get_len(), buf.get_data())); + } + } + return rc; + } +}; + +#endif diff --git a/ccsrc/Framework/include/params.hh b/ccsrc/Framework/include/params.hh index 0bc6398dc5a0a311d18f9677592b35ad9d823179..0418962ba91d71635e7e901d91d22decb09a4842 100644 --- a/ccsrc/Framework/include/params.hh +++ b/ccsrc/Framework/include/params.hh @@ -1,137 +1,137 @@ -/*! - * \file params.hh - * \brief Header file for the parameter dictionary. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include - -/*! - * \class params - * \brief This class provides basic functionalities for an ITS dictionary - * \implements std::map - */ -class params : public std::map { -public: //! \publicsection - // TODO Use static constexpr (see commsignia_layer.hh) - static const std::string& debug; //! Set to 1 to enable the debug mode - - static const std::string& loopback; - - static const std::string& mac_src; //! Source MAC address parameter name - static const std::string& mac_dst; //! Destination MAC address parameter name - static const std::string& mac_bc; //! Broadcast MAC address parameter name - static const std::string& eth_type; //! Ethernet type parameter name - static const std::string& beaconing; //! Beaconing mode parameter name - static const std::string& timestamp; //! Packet reception timestamp - static const std::string& station_type; - static const std::string& country; - static const std::string& type_of_address; - static const std::string& ssp; //! SSP parameter name - static const std::string& its_aid; //! ITS-AID parameter name - static const std::string& gn_payload; //! GeoNetworking Payload parameter name - static const std::string& gn_next_header; //! GeoNetworking NextHeader parameter name - static const std::string& gn_header_type; //! GeoNetworking HeaderType parameter name - static const std::string& gn_header_sub_type; //! GeoNetworking HeaderSubType parameter name - static const std::string& gn_lifetime; //! GeoNetworking Lifetime parameter name - static const std::string& gn_traffic_class; //! GeoNetworking Traffic class parameter name - static const std::string& btp_type; //! BTP Type parameter name - static const std::string& btp_payload; //! BTP Payload parameter name - static const std::string& btp_destination_port; //! BTP DestinationPort parameter name - static const std::string& btp_info; //! BTP Info parameter name - - static const std::string& nic; //! Network Interface Card parameter name - static const std::string& ll_address; //! Test system GeoNetworking LL-Address parameter name - static const std::string& latitude; //! Test system Latitude parameter name - static const std::string& longitude; //! Test system Longitude parameter name - static const std::string& expiry; //! Test system GeoNetworking Lifetime parameter name (in ms) - - static const std::string& station_id; //! To indicate to the peer ITS_Container::stationID - - static const std::string& device_mode; //! To indicate to the lower layer to act as a standalone device - static const std::string& secured_mode; //! To indicate to the lower layer to apply signature on message exchanges as defined in IEEE 1609.2& ETSI TS 102 965 - static const std::string - & encrypted_mode; //! To indicate to the lower layer to apply encryption on message exchanges as defined in IEEE 1609.2& ETSI TS 102 965 - static const std::string& enable_security_checks; //! To indicates if security check failures shall be treated as error or warning - static const std::string& sec_db_path; //! Path to the folder containing certificates - static const std::string& certificate; //! The certificate identifier the Test System shall use. E.g. CERT_TS_A - static const std::string& peer_certificate; //! The peer certificate identifier the Test System shall use for encryption. E.g. CERT_TS_A - static const std::string& hash; //! The digest algorithm the Test System shall use, authorised values are SHA-256 or SHA-384. Default: SHA-256 - static const std::string& signature; //! The signature algorithm the Test System shall use, authorised values are NISTP-256, BP-256 and BP-384. Default: NISTP-256 - static const std::string& cypher; //! The encryption algorithm the Test System shall use, authorised values are NISTP-256 and BP-256. Default: NISTP-256 - static const std::string& distanceA; //! Test system GeoNetworking DistanceA parameter name - static const std::string& distanceB; //! Test system GeoNetworking DistanceB parameter name - static const std::string& angle; //! Test system GeoNetworking Angle parameter name - - static const std::string& payload_type; //! Tyoe of payload, value is the ITS Conatainer message identifier or omitted in case of unknown payload - - static const std::string& next_header; //! Upper layer settings - static const std::string& header_type; //! Upper layer settings - static const std::string& header_sub_type; //! Upper layer settings - - static const std::string& interface_id; //! Commsignia antenna selector - - static const std::string& server; //! HTTP server address (e.g. www.etsi.org) - static const std::string& port; //! HTTP server port. Default: 80 - static const std::string& use_ssl; //! Set to 1 to use SSL to communicate with the HTTP server. Default: false - static const std::string& mutual_auth; //! Set to 1 to use mutual authentication. Default: false - static const std::string& trusted_ca_list; //! List of trusted CA certificates - static const std::string& server_mode; //! Does the test sytem acting as a server. Default: 0 - static const std::string& local_port; //! Local listener port. Default: 80 - - static const std::string& method; //! HTTP method type. Default: POST - static const std::string& uri; //! HTTP URI value. Default: / - static const std::string& host; //! HTTP Host value. Default: 127.0.0.1 - static const std::string& content_type; //! HTTP Content-type value. Default: application/text - - static const std::string& codecs; //! List of codecs to use for HTTP application layers - - /*! - * \brief Default constructor - * Create a new instance of the params class - */ - params() : std::map(){}; - /*! - * \brief Copy constructor - * Clone an existing instance of a params object - * \param[in] p_params An existing instance of a params object - */ - explicit params(const params &p_params) : std::map(p_params.begin(), p_params.end()){}; - - /*! - * \brief Default destructor - */ - virtual ~params(){}; - - /*! - * \fn void log() const; - * \brief Provides a dump of the content of this instance - */ - void log() const; - /*! - * \fn void log() const; - * \brief Provides a dump of the content of this instance - */ - void log(); - /*! - * \fn void reset(); - * \brief Reset the content of this instance - */ - void reset(); - - /*! - * \static - * \fn void convert(params& p_param, const std::string p_parameters); - * \brief Create a new instance of a params object by converting a list of ITS parameters in string format (t1=v1,T2=(v0,v1v2)...) - * \return a new instance of a params object - */ - static void convert(params &p_param, const std::string p_parameters); -}; // End of class params +/*! + * \file params.hh + * \brief Header file for the parameter dictionary. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include + +/*! + * \class params + * \brief This class provides basic functionalities for an ITS dictionary + * \implements std::map + */ +class params : public std::map { +public: //! \publicsection + // TODO Use static constexpr (see commsignia_layer.hh) + static const std::string& debug; //! Set to 1 to enable the debug mode + + static const std::string& loopback; + + static const std::string& mac_src; //! Source MAC address parameter name + static const std::string& mac_dst; //! Destination MAC address parameter name + static const std::string& mac_bc; //! Broadcast MAC address parameter name + static const std::string& eth_type; //! Ethernet type parameter name + static const std::string& beaconing; //! Beaconing mode parameter name + static const std::string& timestamp; //! Packet reception timestamp + static const std::string& station_type; + static const std::string& country; + static const std::string& type_of_address; + static const std::string& ssp; //! SSP parameter name + static const std::string& its_aid; //! ITS-AID parameter name + static const std::string& gn_payload; //! GeoNetworking Payload parameter name + static const std::string& gn_next_header; //! GeoNetworking NextHeader parameter name + static const std::string& gn_header_type; //! GeoNetworking HeaderType parameter name + static const std::string& gn_header_sub_type; //! GeoNetworking HeaderSubType parameter name + static const std::string& gn_lifetime; //! GeoNetworking Lifetime parameter name + static const std::string& gn_traffic_class; //! GeoNetworking Traffic class parameter name + static const std::string& btp_type; //! BTP Type parameter name + static const std::string& btp_payload; //! BTP Payload parameter name + static const std::string& btp_destination_port; //! BTP DestinationPort parameter name + static const std::string& btp_info; //! BTP Info parameter name + + static const std::string& nic; //! Network Interface Card parameter name + static const std::string& ll_address; //! Test system GeoNetworking LL-Address parameter name + static const std::string& latitude; //! Test system Latitude parameter name + static const std::string& longitude; //! Test system Longitude parameter name + static const std::string& expiry; //! Test system GeoNetworking Lifetime parameter name (in ms) + + static const std::string& station_id; //! To indicate to the peer ITS_Container::stationID + + static const std::string& device_mode; //! To indicate to the lower layer to act as a standalone device + static const std::string& secured_mode; //! To indicate to the lower layer to apply signature on message exchanges as defined in IEEE 1609.2& ETSI TS 102 965 + static const std::string + & encrypted_mode; //! To indicate to the lower layer to apply encryption on message exchanges as defined in IEEE 1609.2& ETSI TS 102 965 + static const std::string& enable_security_checks; //! To indicates if security check failures shall be treated as error or warning + static const std::string& sec_db_path; //! Path to the folder containing certificates + static const std::string& certificate; //! The certificate identifier the Test System shall use. E.g. CERT_TS_A + static const std::string& peer_certificate; //! The peer certificate identifier the Test System shall use for encryption. E.g. CERT_TS_A + static const std::string& hash; //! The digest algorithm the Test System shall use, authorised values are SHA-256 or SHA-384. Default: SHA-256 + static const std::string& signature; //! The signature algorithm the Test System shall use, authorised values are NISTP-256, BP-256 and BP-384. Default: NISTP-256 + static const std::string& cypher; //! The encryption algorithm the Test System shall use, authorised values are NISTP-256 and BP-256. Default: NISTP-256 + static const std::string& distanceA; //! Test system GeoNetworking DistanceA parameter name + static const std::string& distanceB; //! Test system GeoNetworking DistanceB parameter name + static const std::string& angle; //! Test system GeoNetworking Angle parameter name + + static const std::string& payload_type; //! Tyoe of payload, value is the ITS Conatainer message identifier or omitted in case of unknown payload + + static const std::string& next_header; //! Upper layer settings + static const std::string& header_type; //! Upper layer settings + static const std::string& header_sub_type; //! Upper layer settings + + static const std::string& interface_id; //! Commsignia antenna selector + + static const std::string& server; //! HTTP server address (e.g. www.etsi.org) + static const std::string& port; //! HTTP server port. Default: 80 + static const std::string& use_ssl; //! Set to 1 to use SSL to communicate with the HTTP server. Default: false + static const std::string& mutual_auth; //! Set to 1 to use mutual authentication. Default: false + static const std::string& trusted_ca_list; //! List of trusted CA certificates + static const std::string& server_mode; //! Does the test sytem acting as a server. Default: 0 + static const std::string& local_port; //! Local listener port. Default: 80 + + static const std::string& method; //! HTTP method type. Default: POST + static const std::string& uri; //! HTTP URI value. Default: / + static const std::string& host; //! HTTP Host value. Default: 127.0.0.1 + static const std::string& content_type; //! HTTP Content-type value. Default: application/text + + static const std::string& codecs; //! List of codecs to use for HTTP application layers + + /*! + * \brief Default constructor + * Create a new instance of the params class + */ + params() : std::map(){}; + /*! + * \brief Copy constructor + * Clone an existing instance of a params object + * \param[in] p_params An existing instance of a params object + */ + explicit params(const params &p_params) : std::map(p_params.begin(), p_params.end()){}; + + /*! + * \brief Default destructor + */ + virtual ~params(){}; + + /*! + * \fn void log() const; + * \brief Provides a dump of the content of this instance + */ + void log() const; + /*! + * \fn void log() const; + * \brief Provides a dump of the content of this instance + */ + void log(); + /*! + * \fn void reset(); + * \brief Reset the content of this instance + */ + void reset(); + + /*! + * \static + * \fn void convert(params& p_param, const std::string p_parameters); + * \brief Create a new instance of a params object by converting a list of ITS parameters in string format (t1=v1,T2=(v0,v1v2)...) + * \return a new instance of a params object + */ + static void convert(params &p_param, const std::string p_parameters); +}; // End of class params diff --git a/ccsrc/Framework/include/per_codec.hh b/ccsrc/Framework/include/per_codec.hh index b5fadb4de7c3e65880a387660db51b70f7da9628..077d74ad549b648d3deccc599e6039cb496a76eb 100644 --- a/ccsrc/Framework/include/per_codec.hh +++ b/ccsrc/Framework/include/per_codec.hh @@ -1,50 +1,50 @@ -/*! - * \file per_codec.hh - * \brief Header file for TITAN message to ASN.1 PER message codec. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "asn1_recode_per.hh" -#include "params.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class TTCN_Typedescriptor_t; //! Forward declaration of TITAN class - -struct asn_TYPE_descriptor_s; //! Declare asn1c class - -/*! - * \class per_codec - * \brief This class provides the interface for all ASN.1 PER codecs. - * \remark This class uses asn1c external tool - */ -template class per_codec : public asn1_recode_per { -public: //! \publicsection - /*! - * \fn int encode(const TPDU& p_message, BITSTRING& p_bitstring); - * \brief Encode TITAN message into ASN.1 PER message - * \param[in] p_message The PDU message to encode - * \param[out] p_bitstring The encoded PDU message in bit string format - * \pure - */ - virtual int encode(const TPDU &p_message, BITSTRING &p_bitstring) = 0; - /*! - * \fn int decode(const BITSTRING& p_bitstring, TPDU& p_message); - * \brief Decode ASN.1 PER message into TITAN message - * \param[in] p_bitstring The network message in bit string format to decode - * \param[out] p_message The PDU message - * \pure - */ - virtual int decode(const BITSTRING &p_bitstring, TPDU &p_message) = 0; - -protected: //! \protectedsection - int _decode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const BITSTRING &p_data, TPDU &msg); - int _encode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const TPDU &msg, BITSTRING &p_data); -}; // End of class per_codec - -#include "per_codec.t.hh" +/*! + * \file per_codec.hh + * \brief Header file for TITAN message to ASN.1 PER message codec. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "asn1_recode_per.hh" +#include "params.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class TTCN_Typedescriptor_t; //! Forward declaration of TITAN class + +struct asn_TYPE_descriptor_s; //! Declare asn1c class + +/*! + * \class per_codec + * \brief This class provides the interface for all ASN.1 PER codecs. + * \remark This class uses asn1c external tool + */ +template class per_codec : public asn1_recode_per { +public: //! \publicsection + /*! + * \fn int encode(const TPDU& p_message, BITSTRING& p_bitstring); + * \brief Encode TITAN message into ASN.1 PER message + * \param[in] p_message The PDU message to encode + * \param[out] p_bitstring The encoded PDU message in bit string format + * \pure + */ + virtual int encode(const TPDU &p_message, BITSTRING &p_bitstring) = 0; + /*! + * \fn int decode(const BITSTRING& p_bitstring, TPDU& p_message); + * \brief Decode ASN.1 PER message into TITAN message + * \param[in] p_bitstring The network message in bit string format to decode + * \param[out] p_message The PDU message + * \pure + */ + virtual int decode(const BITSTRING &p_bitstring, TPDU &p_message) = 0; + +protected: //! \protectedsection + int _decode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const BITSTRING &p_data, TPDU &msg); + int _encode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const TPDU &msg, BITSTRING &p_data); +}; // End of class per_codec + +#include "per_codec.t.hh" diff --git a/ccsrc/Framework/include/per_codec.t.hh b/ccsrc/Framework/include/per_codec.t.hh index e9dace95ab8baf0df64436d2141cb18863ae6296..6973dc6d7c32a9b8252ae75681081d66cd23e498 100644 --- a/ccsrc/Framework/include/per_codec.t.hh +++ b/ccsrc/Framework/include/per_codec.t.hh @@ -1,26 +1,26 @@ -#include - -template int per_codec::_decode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const BITSTRING &p_data, TPDU &msg) { - TTCN_Buffer buf(bit2oct(p_data)); - TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); - int rc = per2ber(td, buf); - if (rc > 0) { - msg.decode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ACCEPT_ALL); - rc = buf.get_len(); - } - return rc; -} - -template int per_codec::_encode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const TPDU &msg, BITSTRING &p_data) { - int rc = -1; - TTCN_Buffer buf; - TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); - msg.encode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ENCODE_DER); - if (buf.get_len() > 0) { - rc = ber2per(td, buf); - if (rc > 0) { - p_data = oct2bit(OCTETSTRING(buf.get_len(), buf.get_data())); - } - } - return rc; -} +#include + +template int per_codec::_decode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const BITSTRING &p_data, TPDU &msg) { + TTCN_Buffer buf(bit2oct(p_data)); + TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); + int rc = per2ber(td, buf); + if (rc > 0) { + msg.decode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ACCEPT_ALL); + rc = buf.get_len(); + } + return rc; +} + +template int per_codec::_encode(const TTCN_Typedescriptor_t &ttcn, const asn_TYPE_descriptor_s &td, const TPDU &msg, BITSTRING &p_data) { + int rc = -1; + TTCN_Buffer buf; + TTCN_EncDec::set_error_behavior(TTCN_EncDec::ET_ALL, TTCN_EncDec::EB_WARNING); + msg.encode(ttcn, buf, TTCN_EncDec::CT_BER, BER_ENCODE_DER); + if (buf.get_len() > 0) { + rc = ber2per(td, buf); + if (rc > 0) { + p_data = oct2bit(OCTETSTRING(buf.get_len(), buf.get_data())); + } + } + return rc; +} diff --git a/ccsrc/Framework/include/registration.hh b/ccsrc/Framework/include/registration.hh index 7da129d443476a5770cdf629ffc7faee77b1db98..df24ea1cfdd3b14c171de8a6f375b80d5e689c15 100644 --- a/ccsrc/Framework/include/registration.hh +++ b/ccsrc/Framework/include/registration.hh @@ -1,58 +1,58 @@ -/*! - * \file registration.hh - * \brief Header file for the control port registration functionality. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include - -/** - * \class registration - * \brief This class provides a way to register items and its object reference - * The registered items are accessible from any object (singleton pattern) - * \remark There is one limitation: each item is uniquely defined in the process - */ -template class registration { // TODO Refine the naming, derive from std::map - std::map _items; - - static registration *_instance; - -private: - registration() : _items(){}; // can not be created manually -public: - static registration &get_instance(); - - virtual ~registration() { - if (_instance != nullptr) - delete _instance; - }; - -public: - void add_item(const std::string &type, TItem *f); - TItem *get_item(const std::string &type); -}; // End of class registration - -template registration *registration::_instance = nullptr; - -// static functions -template registration ®istration::get_instance() { - return (_instance != nullptr) ? *_instance : *(_instance = new registration()); -} - -template void registration::add_item(const std::string &type, TItem *f) { _items[type] = f; } - -template TItem *registration::get_item(const std::string &type) { - typename std::map::const_iterator it = _items.find(type); - if (it == _items.cend()) { - return nullptr; - } - - return it->second; -} // End of class registration +/*! + * \file registration.hh + * \brief Header file for the control port registration functionality. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include + +/** + * \class registration + * \brief This class provides a way to register items and its object reference + * The registered items are accessible from any object (singleton pattern) + * \remark There is one limitation: each item is uniquely defined in the process + */ +template class registration { // TODO Refine the naming, derive from std::map + std::map _items; + + static registration *_instance; + +private: + registration() : _items(){}; // can not be created manually +public: + static registration &get_instance(); + + virtual ~registration() { + if (_instance != nullptr) + delete _instance; + }; + +public: + void add_item(const std::string &type, TItem *f); + TItem *get_item(const std::string &type); +}; // End of class registration + +template registration *registration::_instance = nullptr; + +// static functions +template registration ®istration::get_instance() { + return (_instance != nullptr) ? *_instance : *(_instance = new registration()); +} + +template void registration::add_item(const std::string &type, TItem *f) { _items[type] = f; } + +template TItem *registration::get_item(const std::string &type) { + typename std::map::const_iterator it = _items.find(type); + if (it == _items.cend()) { + return nullptr; + } + + return it->second; +} // End of class registration diff --git a/ccsrc/Framework/include/t_layer.hh b/ccsrc/Framework/include/t_layer.hh index a55a1847d0e1b0c462a648c34bbda0d60f86ed9b..2934952dd15ce1ca69d659a6628b7fab1e5e5b81 100644 --- a/ccsrc/Framework/include/t_layer.hh +++ b/ccsrc/Framework/include/t_layer.hh @@ -1,70 +1,70 @@ -/*! - * \file t_layer.hh - * \brief Header file for ITS abstract protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer.hh" - -/*! - * \class t_layer - * \brief This class provides basic description of an ITS port protocol layer. - * A port protocol layer is the final layer which provides the access to the physical communication channel - * A port protocol layer derives from both a layer class and a template port class - */ -template class t_layer : public layer { - typedef std::vector TPortList; - typedef typename std::vector::iterator TPortListIterator; - - TPortList upperPorts; //! The list of the upper ports - -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the t_layer class - * \todo Remove logs - */ - explicit t_layer() : layer(), upperPorts(){}; - - /*! - * \brief Specialized constructor - * Create a new instance of the layer class with its type description - * \param[in] p_type The port type name (e.g. TCP for the TCP sockect based layer) - * \remark This constructor is called by the layer factory - * \see layer_factory - */ - explicit t_layer(const std::string &p_type) : layer(p_type), upperPorts(){}; - /*! - * \inline - * \fn void add_upper_port(TPort * p_port); - * \brief Add a new upper port layer - * \todo To be done - */ - inline void add_upper_port(TPort *p_port) { upperPorts.push_back(p_port); }; - /*! - * \fn void remove_upper_port(TPort*); - * \brief Remove the specified upper layer port protocol from the list of the upper layers - * \param[in] p_layer The layer protocol to be removed - */ - void remove_upper_port(TPort *); - -protected: //! \protectedsection - /*! - * \inline - * \fn void to_all_upper_ports(const TMessage& m, const params& param); - * \brief Forward the message to all available upper port layers - * \param[in] p_message The message to be forwarded - * \param[in] p_params Some lower layers parameters values when data was received - */ - template inline void to_all_upper_ports(const TMessage &p_message, const params &p_params) { - for (TPortListIterator it = upperPorts.begin(); it < upperPorts.end(); ++it) { - (*it)->receiveMsg(p_message, p_params); - } - } -}; // End of class t_layer +/*! + * \file t_layer.hh + * \brief Header file for ITS abstract protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer.hh" + +/*! + * \class t_layer + * \brief This class provides basic description of an ITS port protocol layer. + * A port protocol layer is the final layer which provides the access to the physical communication channel + * A port protocol layer derives from both a layer class and a template port class + */ +template class t_layer : public layer { + typedef std::vector TPortList; + typedef typename std::vector::iterator TPortListIterator; + + TPortList upperPorts; //! The list of the upper ports + +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the t_layer class + * \todo Remove logs + */ + explicit t_layer() : layer(), upperPorts(){}; + + /*! + * \brief Specialized constructor + * Create a new instance of the layer class with its type description + * \param[in] p_type The port type name (e.g. TCP for the TCP sockect based layer) + * \remark This constructor is called by the layer factory + * \see layer_factory + */ + explicit t_layer(const std::string &p_type) : layer(p_type), upperPorts(){}; + /*! + * \inline + * \fn void add_upper_port(TPort * p_port); + * \brief Add a new upper port layer + * \todo To be done + */ + inline void add_upper_port(TPort *p_port) { upperPorts.push_back(p_port); }; + /*! + * \fn void remove_upper_port(TPort*); + * \brief Remove the specified upper layer port protocol from the list of the upper layers + * \param[in] p_layer The layer protocol to be removed + */ + void remove_upper_port(TPort *); + +protected: //! \protectedsection + /*! + * \inline + * \fn void to_all_upper_ports(const TMessage& m, const params& param); + * \brief Forward the message to all available upper port layers + * \param[in] p_message The message to be forwarded + * \param[in] p_params Some lower layers parameters values when data was received + */ + template inline void to_all_upper_ports(const TMessage &p_message, const params &p_params) { + for (TPortListIterator it = upperPorts.begin(); it < upperPorts.end(); ++it) { + (*it)->receiveMsg(p_message, p_params); + } + } +}; // End of class t_layer diff --git a/ccsrc/Framework/module.mk b/ccsrc/Framework/module.mk index b4ca0cee9292d804863078784f7ac461406cc9c2..8592d3c6248cfb7e0cfe63b6d6f59e6f02861ef1 100644 --- a/ccsrc/Framework/module.mk +++ b/ccsrc/Framework/module.mk @@ -1,6 +1,6 @@ -sources := src/base_time.cc \ - src/codec_stack_builder.cc \ - src/converter.cc \ - src/layer_factory.cc \ - src/params.cc -includes += ./include +sources := src/base_time.cc \ + src/codec_stack_builder.cc \ + src/converter.cc \ + src/layer_factory.cc \ + src/params.cc +includes += ./include diff --git a/ccsrc/Framework/src/base_time.cc b/ccsrc/Framework/src/base_time.cc index 79924f86464773a5cc399a63b13a7ffedefdb895..38331193d666b1354b31cdc7b0ebc07ed135734c 100644 --- a/ccsrc/Framework/src/base_time.cc +++ b/ccsrc/Framework/src/base_time.cc @@ -1,13 +1,13 @@ -/*! - * \file base_time.cc - * \brief Source file for the control port base_time functionality. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include "base_time.hh" - -base_time* base_time::_instance = nullptr; +/*! + * \file base_time.cc + * \brief Source file for the control port base_time functionality. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include "base_time.hh" + +base_time* base_time::_instance = nullptr; diff --git a/ccsrc/Framework/src/codec_stack_builder.cc b/ccsrc/Framework/src/codec_stack_builder.cc index 2bf087e4bb7d687b91ab1d1db54da361a2d24d0d..bb5a706667b483e068a92ea24c497d86e0b246bd 100644 --- a/ccsrc/Framework/src/codec_stack_builder.cc +++ b/ccsrc/Framework/src/codec_stack_builder.cc @@ -1,4 +1,4 @@ -#include "codec_stack_builder.hh" - -codec_stack_builder* codec_stack_builder::_instance = NULL; - +#include "codec_stack_builder.hh" + +codec_stack_builder* codec_stack_builder::_instance = NULL; + diff --git a/ccsrc/Framework/src/converter.cc b/ccsrc/Framework/src/converter.cc index c2c4c0bfde7d86cc248621aac3c6f10b365a35bf..e9ad4d1476ff8563e79a712ac1e9eeae18787636 100644 --- a/ccsrc/Framework/src/converter.cc +++ b/ccsrc/Framework/src/converter.cc @@ -1,195 +1,195 @@ -#include "converter.hh" -#include -converter *converter::instance = NULL; - -uint16_t converter::swap(const uint16_t p_value) { - uint8_t *ptr = (uint8_t *)&p_value; - return (ptr[0] << 8) | ptr[1]; -} - -uint32_t converter::swap(const uint32_t p_value) { - uint8_t *ptr = (uint8_t *)&p_value; - return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; -} - -const std::string converter::lut_u = "0123456789ABCDEF"; -const std::string converter::lut_l = "0123456789abcdef"; -std::string converter::string_to_hexa(const std::string &p_value, const bool p_uppercase) { - - std::string input(p_value); - std::for_each(input.begin(), input.end(), [](char &c) { c = std::toupper(c); }); - - std::string output; - uint32_t length = p_value.length(); - output.reserve(2 * length); - if (p_uppercase) { // TODO Use pointer to reduce code size - for (uint32_t i = 0; i < length; ++i) { - const uint8_t c = input[i]; - output.push_back(lut_u[c >> 4]); - output.push_back(lut_u[c & 15]); - } // End of 'for' statement - } else { - for (uint32_t i = 0; i < length; ++i) { - const uint8_t c = input[i]; - output.push_back(lut_l[c >> 4]); - output.push_back(lut_l[c & 15]); - } // End of 'for' statement - } - - return output; -} - -std::string converter::bytes_to_hexa(const std::vector &p_value, const bool p_uppercase) { - std::string ret; - ret.assign(p_value.size() * 2, ' '); - if (p_uppercase) { // TODO Use pointer to reduce code size - for (size_t i = 0; i < p_value.size(); i++) { - uint8_t c = p_value[i]; - ret[i * 2] = lut_u[c >> 4]; - ret[i * 2 + 1] = lut_u[c & 0xF]; - } - } else { - for (size_t i = 0; i < p_value.size(); i++) { - uint8_t c = p_value[i]; - ret[i * 2] = lut_l[c >> 4]; - ret[i * 2 + 1] = lut_l[c & 0xF]; - } - } - return ret; -} - -inline uint8_t char2byte(const char p_ch) { - size_t s = converter::lut_l.find(p_ch); - if (s == std::string::npos) { - if ((s = converter::lut_u.find(p_ch)) == std::string::npos) { - throw(std::length_error("")); - } - } - return s; -} - -std::vector converter::hexa_to_bytes(const std::string &p_value) { - // Sanity check - std::vector output; - size_t i = 0, idx = 0, outlen = (p_value.length() + 1) / 2; - - output.assign(outlen, 0x00); - try { - if (p_value.length() & 1) - output[idx++] = char2byte(p_value[i++]); - for (; idx < outlen; idx++) { - uint8_t b0 = char2byte(p_value[i++]); - uint8_t b1 = char2byte(p_value[i++]); - output[idx] = (b0 << 4) | b1; - } - } catch (const std::length_error &le) { - output.clear(); - } - return output; -} - -std::string converter::time_to_string(const time_t p_time) { - struct tm *t = std::localtime(&p_time); - return time_to_string(*t); -} - -std::string converter::time_to_string(const struct tm &p_time) { - char buffer[64] = {0}; - // Format: RFC 822, 1036, 1123, 2822 - std::strftime(buffer, 64, "%a, %d %b %Y %H:%M:%S %z", &p_time); - return std::string(buffer); -} - -std::string converter::trim(const std::string &str, const std::string &whitespace) { - size_t strBegin = str.find_first_not_of(whitespace); - if (strBegin == std::string::npos) - return ""; // no content - - size_t strEnd = str.find_last_not_of(whitespace); - size_t strRange = strEnd - strBegin + 1; - - return str.substr(strBegin, strRange); -} - -std::vector converter::split(const std::string &p_value, const std::string &p_separator) { - std::vector output; - std::size_t current, previous = 0; - current = p_value.find(p_separator); - while (current != std::string::npos) { - output.push_back(p_value.substr(previous, current - previous)); - previous = current + 1; - current = p_value.find(p_separator, previous); - } - output.push_back(p_value.substr(previous, current - previous)); - - return output; -} - -std::vector converter::split_arguments_line(const std::string &p_value) { - std::vector output; - std::string line = trim(p_value); - if (!line.empty() && (line[0] == '-')) { // Valid command line - size_t current = 0; - size_t next = (size_t)-1; - size_t pos = 0; - do { - if (line[pos + 1] == '-') { // -- - current = pos + 2; - } else { - current = pos + 1; - } - next = line.find("-", current); - std::string str(line.substr(pos, next - pos)); - output.push_back(str); - pos = next; - } while (next != std::string::npos); - } // else, invalid command line - return output; -} - -const std::string converter::base64_enc_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -std::vector converter::buffer_to_base64(const std::vector &p_value) { - std::vector out; - - int val = 0, valb = -6; - for (unsigned char c : p_value) { - val = (val << 8) + c; - valb += 8; - while (valb >= 0) { - out.push_back(converter::base64_enc_map[(val >> valb) & 0x3F]); - valb -= 6; - } // End of 'while' statement - } // End of 'for' statement - if (valb > -6) { - out.push_back(converter::base64_enc_map[((val << 8) >> (valb + 8)) & 0x3F]); - } - while (out.size() % 4) { - out.push_back('='); - } // End of 'while' statement - - return out; -} - -std::vector converter::base64_to_buffer(const std::vector &p_value) { - std::vector out; - - std::vector T(256, -1); - for (int i = 0; i < 64; i++) { - T[converter::base64_enc_map[i]] = i; - } - - int val = 0, valb = -8; - for (unsigned char c : p_value) { - if (T[c] == -1) { - break; - } - val = (val << 6) + T[c]; - valb += 6; - if (valb >= 0) { - out.push_back((unsigned char)char((val >> valb) & 0xFF)); - valb -= 8; - } - } // End of 'for' statement - return out; -} +#include "converter.hh" +#include +converter *converter::instance = NULL; + +uint16_t converter::swap(const uint16_t p_value) { + uint8_t *ptr = (uint8_t *)&p_value; + return (ptr[0] << 8) | ptr[1]; +} + +uint32_t converter::swap(const uint32_t p_value) { + uint8_t *ptr = (uint8_t *)&p_value; + return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; +} + +const std::string converter::lut_u = "0123456789ABCDEF"; +const std::string converter::lut_l = "0123456789abcdef"; +std::string converter::string_to_hexa(const std::string &p_value, const bool p_uppercase) { + + std::string input(p_value); + std::for_each(input.begin(), input.end(), [](char &c) { c = std::toupper(c); }); + + std::string output; + uint32_t length = p_value.length(); + output.reserve(2 * length); + if (p_uppercase) { // TODO Use pointer to reduce code size + for (uint32_t i = 0; i < length; ++i) { + const uint8_t c = input[i]; + output.push_back(lut_u[c >> 4]); + output.push_back(lut_u[c & 15]); + } // End of 'for' statement + } else { + for (uint32_t i = 0; i < length; ++i) { + const uint8_t c = input[i]; + output.push_back(lut_l[c >> 4]); + output.push_back(lut_l[c & 15]); + } // End of 'for' statement + } + + return output; +} + +std::string converter::bytes_to_hexa(const std::vector &p_value, const bool p_uppercase) { + std::string ret; + ret.assign(p_value.size() * 2, ' '); + if (p_uppercase) { // TODO Use pointer to reduce code size + for (size_t i = 0; i < p_value.size(); i++) { + uint8_t c = p_value[i]; + ret[i * 2] = lut_u[c >> 4]; + ret[i * 2 + 1] = lut_u[c & 0xF]; + } + } else { + for (size_t i = 0; i < p_value.size(); i++) { + uint8_t c = p_value[i]; + ret[i * 2] = lut_l[c >> 4]; + ret[i * 2 + 1] = lut_l[c & 0xF]; + } + } + return ret; +} + +inline uint8_t char2byte(const char p_ch) { + size_t s = converter::lut_l.find(p_ch); + if (s == std::string::npos) { + if ((s = converter::lut_u.find(p_ch)) == std::string::npos) { + throw(std::length_error("")); + } + } + return s; +} + +std::vector converter::hexa_to_bytes(const std::string &p_value) { + // Sanity check + std::vector output; + size_t i = 0, idx = 0, outlen = (p_value.length() + 1) / 2; + + output.assign(outlen, 0x00); + try { + if (p_value.length() & 1) + output[idx++] = char2byte(p_value[i++]); + for (; idx < outlen; idx++) { + uint8_t b0 = char2byte(p_value[i++]); + uint8_t b1 = char2byte(p_value[i++]); + output[idx] = (b0 << 4) | b1; + } + } catch (const std::length_error &le) { + output.clear(); + } + return output; +} + +std::string converter::time_to_string(const time_t p_time) { + struct tm *t = std::localtime(&p_time); + return time_to_string(*t); +} + +std::string converter::time_to_string(const struct tm &p_time) { + char buffer[64] = {0}; + // Format: RFC 822, 1036, 1123, 2822 + std::strftime(buffer, 64, "%a, %d %b %Y %H:%M:%S %z", &p_time); + return std::string(buffer); +} + +std::string converter::trim(const std::string &str, const std::string &whitespace) { + size_t strBegin = str.find_first_not_of(whitespace); + if (strBegin == std::string::npos) + return ""; // no content + + size_t strEnd = str.find_last_not_of(whitespace); + size_t strRange = strEnd - strBegin + 1; + + return str.substr(strBegin, strRange); +} + +std::vector converter::split(const std::string &p_value, const std::string &p_separator) { + std::vector output; + std::size_t current, previous = 0; + current = p_value.find(p_separator); + while (current != std::string::npos) { + output.push_back(p_value.substr(previous, current - previous)); + previous = current + 1; + current = p_value.find(p_separator, previous); + } + output.push_back(p_value.substr(previous, current - previous)); + + return output; +} + +std::vector converter::split_arguments_line(const std::string &p_value) { + std::vector output; + std::string line = trim(p_value); + if (!line.empty() && (line[0] == '-')) { // Valid command line + size_t current = 0; + size_t next = (size_t)-1; + size_t pos = 0; + do { + if (line[pos + 1] == '-') { // -- + current = pos + 2; + } else { + current = pos + 1; + } + next = line.find("-", current); + std::string str(line.substr(pos, next - pos)); + output.push_back(str); + pos = next; + } while (next != std::string::npos); + } // else, invalid command line + return output; +} + +const std::string converter::base64_enc_map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +std::vector converter::buffer_to_base64(const std::vector &p_value) { + std::vector out; + + int val = 0, valb = -6; + for (unsigned char c : p_value) { + val = (val << 8) + c; + valb += 8; + while (valb >= 0) { + out.push_back(converter::base64_enc_map[(val >> valb) & 0x3F]); + valb -= 6; + } // End of 'while' statement + } // End of 'for' statement + if (valb > -6) { + out.push_back(converter::base64_enc_map[((val << 8) >> (valb + 8)) & 0x3F]); + } + while (out.size() % 4) { + out.push_back('='); + } // End of 'while' statement + + return out; +} + +std::vector converter::base64_to_buffer(const std::vector &p_value) { + std::vector out; + + std::vector T(256, -1); + for (int i = 0; i < 64; i++) { + T[converter::base64_enc_map[i]] = i; + } + + int val = 0, valb = -8; + for (unsigned char c : p_value) { + if (T[c] == -1) { + break; + } + val = (val << 6) + T[c]; + valb += 6; + if (valb >= 0) { + out.push_back((unsigned char)char((val >> valb) & 0xFF)); + valb -= 8; + } + } // End of 'for' statement + return out; +} diff --git a/ccsrc/Framework/src/layer_factory.cc b/ccsrc/Framework/src/layer_factory.cc index a015b9cfc2c795cfdec0e18129a6733f8c13c8dd..ef3ad213e9a3d898f58eafa9aff85ad667754267 100644 --- a/ccsrc/Framework/src/layer_factory.cc +++ b/ccsrc/Framework/src/layer_factory.cc @@ -1,61 +1,61 @@ -#include -#include - -#include "layer_stack_builder.hh" - -#include "loggers.hh" - -layer_stack_builder *layer_stack_builder::_instance = NULL; - -// static functions -layer_stack_builder *layer_stack_builder::get_instance() { return _instance ? _instance : _instance = new layer_stack_builder(); } - -void layer_stack_builder::register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory) { - layer_stack_builder::get_instance()->_register_layer_factory(p_type, p_layer_factory); -} - -// member functions -layer_stack_builder::layer_stack_builder() {} - -void layer_stack_builder::_register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory) { _layer_factories[p_type] = p_layer_factory; } - -layer *layer_stack_builder::create_layer_stack(const char *p_layer_stack_description) { - loggers::get_instance().log(">>> layer_stack_builder::create_layer_stack: %s", p_layer_stack_description); - - layer *entry = NULL; // Initial layer (the first declared) - layer *up = NULL; // Upper layer - // Parse the layer description - try { - std::regex rgx("(\\w+)(\\((.*?)\\))?(\\/|$)"); - std::string str = p_layer_stack_description; - std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); - std::sregex_iterator end = std::sregex_iterator(); - for (std::sregex_iterator it = begin; it != end; ++it) { - std::smatch m = *it; - loggers::get_instance().log("layer_stack_builder::create_layer_stack: %d - %s - %s - %s - %s", m.size(), m[0].str().c_str(), m[1].str().c_str(), - m[2].str().c_str(), m[3].str().c_str()); - LayerFactoryMap::iterator i = _layer_factories.find(m[1].str()); - if (i == _layer_factories.end()) { - loggers::get_instance().error("layer_stack_builder::create_layer_stack: %s: Unknown layer type", m[1].str().c_str()); - } - loggers::get_instance().log("layer_stack_builder::create_layer_stack: Create layer %s, %s", m[1].str().c_str(), m[3].str().c_str()); - layer *l = i->second->create_layer(m[1].str(), m[3].str()); - if (NULL == l) { - loggers::get_instance().error("layer_stack_builder::create_layer_stack: %s: Layer creation error", m[1].str().c_str()); - } - - loggers::get_instance().log("layer_stack_builder::create_layer_stack: Setup layers for %s", l->to_string().c_str()); - l->add_upper_layer(up); - if (entry == NULL) { // Set the first declared layer - entry = l; - } - up = l; // Build the linked list of layers - } // End of 'for' statement - } catch (const std::logic_error &e) { - if (up) { // FIXME To be reviewed - up->delete_layer(); - up = NULL; - } - } - return entry; -} +#include +#include + +#include "layer_stack_builder.hh" + +#include "loggers.hh" + +layer_stack_builder *layer_stack_builder::_instance = NULL; + +// static functions +layer_stack_builder *layer_stack_builder::get_instance() { return _instance ? _instance : _instance = new layer_stack_builder(); } + +void layer_stack_builder::register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory) { + layer_stack_builder::get_instance()->_register_layer_factory(p_type, p_layer_factory); +} + +// member functions +layer_stack_builder::layer_stack_builder() {} + +void layer_stack_builder::_register_layer_factory(const std::string &p_type, layer_factory *p_layer_factory) { _layer_factories[p_type] = p_layer_factory; } + +layer *layer_stack_builder::create_layer_stack(const char *p_layer_stack_description) { + loggers::get_instance().log(">>> layer_stack_builder::create_layer_stack: %s", p_layer_stack_description); + + layer *entry = NULL; // Initial layer (the first declared) + layer *up = NULL; // Upper layer + // Parse the layer description + try { + std::regex rgx("(\\w+)(\\((.*?)\\))?(\\/|$)"); + std::string str = p_layer_stack_description; + std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); + std::sregex_iterator end = std::sregex_iterator(); + for (std::sregex_iterator it = begin; it != end; ++it) { + std::smatch m = *it; + loggers::get_instance().log("layer_stack_builder::create_layer_stack: %d - %s - %s - %s - %s", m.size(), m[0].str().c_str(), m[1].str().c_str(), + m[2].str().c_str(), m[3].str().c_str()); + LayerFactoryMap::iterator i = _layer_factories.find(m[1].str()); + if (i == _layer_factories.end()) { + loggers::get_instance().error("layer_stack_builder::create_layer_stack: %s: Unknown layer type", m[1].str().c_str()); + } + loggers::get_instance().log("layer_stack_builder::create_layer_stack: Create layer %s, %s", m[1].str().c_str(), m[3].str().c_str()); + layer *l = i->second->create_layer(m[1].str(), m[3].str()); + if (NULL == l) { + loggers::get_instance().error("layer_stack_builder::create_layer_stack: %s: Layer creation error", m[1].str().c_str()); + } + + loggers::get_instance().log("layer_stack_builder::create_layer_stack: Setup layers for %s", l->to_string().c_str()); + l->add_upper_layer(up); + if (entry == NULL) { // Set the first declared layer + entry = l; + } + up = l; // Build the linked list of layers + } // End of 'for' statement + } catch (const std::logic_error &e) { + if (up) { // FIXME To be reviewed + up->delete_layer(); + up = NULL; + } + } + return entry; +} diff --git a/ccsrc/Framework/src/params.cc b/ccsrc/Framework/src/params.cc index 13b16faa4c82b81ac605aab88af3a36a662f369f..f99aa7d7ad0cd5e941cf472b834725833eb6268d 100644 --- a/ccsrc/Framework/src/params.cc +++ b/ccsrc/Framework/src/params.cc @@ -1,143 +1,143 @@ -/*! - * \file params.cc - * \brief Source file for the parameter dictionary. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include -#include - -#include "loggers.hh" -#include "params.hh" - -const std::string& params::debug = std::string("debug"); - -const std::string& params::loopback = std::string("loopback"); - -const std::string& params::mac_src = std::string("mac_src"); -const std::string& params::mac_dst = std::string("mac_dst"); -const std::string& params::mac_bc = std::string("mac_bc"); -const std::string& params::eth_type = std::string("eth_type"); -const std::string& params::beaconing = std::string("beaconing"); -const std::string& params::timestamp = std::string("timestamp"); -const std::string& params::station_type = std::string("station_type"); -const std::string& params::country = std::string("country"); -const std::string& params::type_of_address = std::string("type_of_address"); -const std::string& params::its_aid = std::string("its_aid"); -const std::string& params::ssp = std::string("ssp"); -const std::string& params::gn_payload = std::string("gn_payload"); -const std::string& params::gn_next_header = std::string("gnNextHeader"); -const std::string& params::gn_header_type = std::string("gnHeaderType"); -const std::string& params::gn_header_sub_type = std::string("gnHeaderSubtype"); -const std::string& params::gn_lifetime = std::string("gnLifetime"); -const std::string& params::gn_traffic_class = std::string("gnTrafficClass"); -const std::string& params::btp_type = std::string("btp_type"); -const std::string& params::btp_payload = std::string("btp_payload"); -const std::string& params::btp_destination_port = std::string("dst_port"); -const std::string& params::btp_info = std::string("btp_info"); - -const std::string& params::nic = std::string("nic"); -const std::string& params::latitude = std::string("latitude"); -const std::string& params::longitude = std::string("longitude"); -const std::string& params::ll_address = std::string("ll_address"); -const std::string& params::expiry = std::string("expiry"); - -const std::string& params::station_id = std::string("station_id"); - -const std::string& params::device_mode = std::string("device_mode"); -const std::string& params::secured_mode = std::string("secured_mode"); -const std::string& params::encrypted_mode = std::string("encrypted_mode"); -const std::string& params::enable_security_checks = std::string("enable_security_checks"); -const std::string& params::certificate = std::string("certificate"); -const std::string& params::peer_certificate = std::string("peer_certificate"); -const std::string& params::sec_db_path = std::string("sec_db_path"); -const std::string& params::hash = std::string("hash"); -const std::string& params::signature = std::string("signature"); -const std::string& params::cypher = std::string("cypher"); -const std::string& params::distanceA = std::string("distanceA"); -const std::string& params::distanceB = std::string("distanceB"); -const std::string& params::angle = std::string("angle"); - -const std::string& params::payload_type = std::string("payload_type"); - -const std::string& params::next_header = std::string("next_header"); -const std::string& params::header_type = std::string("header_type"); -const std::string& params::header_sub_type = std::string("header_sub_type"); - -const std::string& params::interface_id = std::string("interface_id"); - -const std::string& params::server = std::string("server"); -const std::string& params::port = std::string("port"); -const std::string& params::use_ssl = std::string("use_ssl"); -const std::string& params::mutual_auth = std::string("mutual_auth"); -const std::string& params::trusted_ca_list = std::string("trusted_ca_list"); - -const std::string& params::server_mode = std::string("server_mode"); -const std::string& params::local_port = std::string("local_port"); - -const std::string& params::method = std::string("method"); -const std::string& params::uri = std::string("uri"); -const std::string& params::host = std::string("host"); -const std::string& params::content_type = std::string("content_type"); - -// const std::string& params::sip_url = std::string("sip_url"); -// const std::string& params::sip_version = std::string("sip_version"); -// const std::string& params::payload = std::string("payload"); - -const std::string& params::codecs = std::string("codecs"); - -void params::convert(params &p_param, const std::string p_parameters) { - // Sanity checks - if (p_parameters.length() == 0) { - return; - } - loggers::get_instance().log(">>> params::convert: %s", p_parameters.c_str()); - // Extract parameters - try { - std::regex rgx("(\\w+)=(.*?)(,|$)"); - std::sregex_iterator begin(p_parameters.cbegin(), p_parameters.cend(), rgx); - std::sregex_iterator end = std::sregex_iterator(); - for (std::sregex_iterator it = begin; it != end; ++it) { - std::smatch m = *it; - loggers::get_instance().log("params::convert: %d - %s - %s - %s - %s", m.size(), m[0].str().c_str(), m[1].str().c_str(), m[2].str().c_str(), - m[3].str().c_str()); - p_param.insert(std::pair(m[1].str(), m[2].str())); - } // End of 'for' statement - } catch (const std::logic_error &e) { - p_param.clear(); - } - loggers::get_instance().log("<<< params::convert"); -} - -void params::log() const { - loggers::get_instance().log("params::log"); - if (size() == 0) { - loggers::get_instance().log("\tEmpty"); - } else { - for (const_iterator it = cbegin(); it != cend(); ++it) { - loggers::get_instance().log("\t(%s, %s)", it->first.c_str(), it->second.c_str()); - } // End of 'for' statement - } -} - -void params::log() { - loggers::get_instance().log("params::log"); - if (size() == 0) { - loggers::get_instance().log("\tEmpty"); - } else { - for (const_iterator it = cbegin(); it != cend(); ++it) { - loggers::get_instance().log("\t(%s, %s)", it->first.c_str(), it->second.c_str()); - } // End of 'for' statement - } -} - -void params::reset() { - loggers::get_instance().log("params::reset"); - for (iterator it = begin(); it != end(); ++it) { - it->second.clear(); - } // End of 'for' statement -} +/*! + * \file params.cc + * \brief Source file for the parameter dictionary. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include +#include + +#include "loggers.hh" +#include "params.hh" + +const std::string& params::debug = std::string("debug"); + +const std::string& params::loopback = std::string("loopback"); + +const std::string& params::mac_src = std::string("mac_src"); +const std::string& params::mac_dst = std::string("mac_dst"); +const std::string& params::mac_bc = std::string("mac_bc"); +const std::string& params::eth_type = std::string("eth_type"); +const std::string& params::beaconing = std::string("beaconing"); +const std::string& params::timestamp = std::string("timestamp"); +const std::string& params::station_type = std::string("station_type"); +const std::string& params::country = std::string("country"); +const std::string& params::type_of_address = std::string("type_of_address"); +const std::string& params::its_aid = std::string("its_aid"); +const std::string& params::ssp = std::string("ssp"); +const std::string& params::gn_payload = std::string("gn_payload"); +const std::string& params::gn_next_header = std::string("gnNextHeader"); +const std::string& params::gn_header_type = std::string("gnHeaderType"); +const std::string& params::gn_header_sub_type = std::string("gnHeaderSubtype"); +const std::string& params::gn_lifetime = std::string("gnLifetime"); +const std::string& params::gn_traffic_class = std::string("gnTrafficClass"); +const std::string& params::btp_type = std::string("btp_type"); +const std::string& params::btp_payload = std::string("btp_payload"); +const std::string& params::btp_destination_port = std::string("dst_port"); +const std::string& params::btp_info = std::string("btp_info"); + +const std::string& params::nic = std::string("nic"); +const std::string& params::latitude = std::string("latitude"); +const std::string& params::longitude = std::string("longitude"); +const std::string& params::ll_address = std::string("ll_address"); +const std::string& params::expiry = std::string("expiry"); + +const std::string& params::station_id = std::string("station_id"); + +const std::string& params::device_mode = std::string("device_mode"); +const std::string& params::secured_mode = std::string("secured_mode"); +const std::string& params::encrypted_mode = std::string("encrypted_mode"); +const std::string& params::enable_security_checks = std::string("enable_security_checks"); +const std::string& params::certificate = std::string("certificate"); +const std::string& params::peer_certificate = std::string("peer_certificate"); +const std::string& params::sec_db_path = std::string("sec_db_path"); +const std::string& params::hash = std::string("hash"); +const std::string& params::signature = std::string("signature"); +const std::string& params::cypher = std::string("cypher"); +const std::string& params::distanceA = std::string("distanceA"); +const std::string& params::distanceB = std::string("distanceB"); +const std::string& params::angle = std::string("angle"); + +const std::string& params::payload_type = std::string("payload_type"); + +const std::string& params::next_header = std::string("next_header"); +const std::string& params::header_type = std::string("header_type"); +const std::string& params::header_sub_type = std::string("header_sub_type"); + +const std::string& params::interface_id = std::string("interface_id"); + +const std::string& params::server = std::string("server"); +const std::string& params::port = std::string("port"); +const std::string& params::use_ssl = std::string("use_ssl"); +const std::string& params::mutual_auth = std::string("mutual_auth"); +const std::string& params::trusted_ca_list = std::string("trusted_ca_list"); + +const std::string& params::server_mode = std::string("server_mode"); +const std::string& params::local_port = std::string("local_port"); + +const std::string& params::method = std::string("method"); +const std::string& params::uri = std::string("uri"); +const std::string& params::host = std::string("host"); +const std::string& params::content_type = std::string("content_type"); + +// const std::string& params::sip_url = std::string("sip_url"); +// const std::string& params::sip_version = std::string("sip_version"); +// const std::string& params::payload = std::string("payload"); + +const std::string& params::codecs = std::string("codecs"); + +void params::convert(params &p_param, const std::string p_parameters) { + // Sanity checks + if (p_parameters.length() == 0) { + return; + } + loggers::get_instance().log(">>> params::convert: %s", p_parameters.c_str()); + // Extract parameters + try { + std::regex rgx("(\\w+)=(.*?)(,|$)"); + std::sregex_iterator begin(p_parameters.cbegin(), p_parameters.cend(), rgx); + std::sregex_iterator end = std::sregex_iterator(); + for (std::sregex_iterator it = begin; it != end; ++it) { + std::smatch m = *it; + loggers::get_instance().log("params::convert: %d - %s - %s - %s - %s", m.size(), m[0].str().c_str(), m[1].str().c_str(), m[2].str().c_str(), + m[3].str().c_str()); + p_param.insert(std::pair(m[1].str(), m[2].str())); + } // End of 'for' statement + } catch (const std::logic_error &e) { + p_param.clear(); + } + loggers::get_instance().log("<<< params::convert"); +} + +void params::log() const { + loggers::get_instance().log("params::log"); + if (size() == 0) { + loggers::get_instance().log("\tEmpty"); + } else { + for (const_iterator it = cbegin(); it != cend(); ++it) { + loggers::get_instance().log("\t(%s, %s)", it->first.c_str(), it->second.c_str()); + } // End of 'for' statement + } +} + +void params::log() { + loggers::get_instance().log("params::log"); + if (size() == 0) { + loggers::get_instance().log("\tEmpty"); + } else { + for (const_iterator it = cbegin(); it != cend(); ++it) { + loggers::get_instance().log("\t(%s, %s)", it->first.c_str(), it->second.c_str()); + } // End of 'for' statement + } +} + +void params::reset() { + loggers::get_instance().log("params::reset"); + for (iterator it = begin(); it != end(); ++it) { + it->second.clear(); + } // End of 'for' statement +} diff --git a/ccsrc/Ports/LibIts_ports/AdapterControlPort.hh b/ccsrc/Ports/LibIts_ports/AdapterControlPort.hh index a0b36aabd20874c6aaf86825d20a7ff7085836f5..e7d7ab1fede934e50320b61925f9e0285cba3763 100644 --- a/ccsrc/Ports/LibIts_ports/AdapterControlPort.hh +++ b/ccsrc/Ports/LibIts_ports/AdapterControlPort.hh @@ -1,65 +1,65 @@ - -//#include "TRI_mapper_API.hh" - -#ifdef _NO_SOFTLINKS_ -/* to be used when built without generating softlinks to the working directory */ -//#include "CALM_ports/AdapterControlPort_CALM.partH" -#ifdef LibItsCam__TestSystem_HH -#include "CAM_ports/AdapterControlPort_CAM.hh" -#endif -#ifdef LibItsDenm__TestSystem_HH -#include "DENM_ports/AdapterControlPort_DENM.hh" -#endif -#ifdef LibItsGeoNetworking__TestSystem_HH -#include "GN_ports/AdapterControlPort_GN.hh" -#endif -#ifdef LibItsIvim__TestSystem_HH -#include "IVIM_ports/AdapterControlPort_IVIM.hh" -#endif -#ifdef LibItsMapemSpatem__TestSystem_HH -#include "MapemSpatem_ports/AdapterControlPort_MapemSpatem.hh" -#endif -#ifdef LibItsSremSsem__TestSystem_HH -#include "SremSsem_ports/AdapterControlPort_SremSsem.hh" -#endif -#ifdef LibItsRtcmem__TestSystem_HH -#include "Rtcmem_ports/AdapterControlPort_Rtcmem.hh" -#endif -#ifdef LibItsV2G__TestSystem_HH -#include "V2G_ports/AdapterControlPort_V2G.hh" -#endif -//#ifdef LibItsPki__TestSystem_HH -//#include "Pki_ports/AdapterControlPort_Pki.hh" -//#endif - -#else //_NO_SOFTLINKS_ - -#ifdef LibItsCam__TestSystem_HH -#include "AdapterControlPort_CAM.hh" -#endif -#ifdef LibItsDenm__TestSystem_HH -#include "AdapterControlPort_DENM.hh" -#endif -#ifdef LibItsIvim__TestSystem_HH -#include "AdapterControlPort_IVIM.hh" -#endif -#ifdef LibItsMapemSpatem__TestSystem_HH -#include "AdapterControlPort_MapemSpatem.hh" -#endif -#ifdef LibItsSremSsem__TestSystem_HH -#include "AdapterControlPort_SremSsem.hh" -#endif -#ifdef LibItsRtcmem__TestSystem_HH -#include "AdapterControlPort_Rtcmem.hh" -#endif -#ifdef LibItsGeoNetworking__TestSystem_HH -#include "AdapterControlPort_GN.hh" -#endif -/* -#include "AdapterControlPort_Evcsn.partH" -#include "AdapterControlPort_IVIM.partH" -#include "AdapterControlPort_MapemSpatem.partH" -#include "AdapterControlPort_SremSsem.partH" -*/ -//#include "AdapterControlPort_V2G.partH" -#endif //_NO_SOFTLINKS_ + +//#include "TRI_mapper_API.hh" + +#ifdef _NO_SOFTLINKS_ +/* to be used when built without generating softlinks to the working directory */ +//#include "CALM_ports/AdapterControlPort_CALM.partH" +#ifdef LibItsCam__TestSystem_HH +#include "CAM_ports/AdapterControlPort_CAM.hh" +#endif +#ifdef LibItsDenm__TestSystem_HH +#include "DENM_ports/AdapterControlPort_DENM.hh" +#endif +#ifdef LibItsGeoNetworking__TestSystem_HH +#include "GN_ports/AdapterControlPort_GN.hh" +#endif +#ifdef LibItsIvim__TestSystem_HH +#include "IVIM_ports/AdapterControlPort_IVIM.hh" +#endif +#ifdef LibItsMapemSpatem__TestSystem_HH +#include "MapemSpatem_ports/AdapterControlPort_MapemSpatem.hh" +#endif +#ifdef LibItsSremSsem__TestSystem_HH +#include "SremSsem_ports/AdapterControlPort_SremSsem.hh" +#endif +#ifdef LibItsRtcmem__TestSystem_HH +#include "Rtcmem_ports/AdapterControlPort_Rtcmem.hh" +#endif +#ifdef LibItsV2G__TestSystem_HH +#include "V2G_ports/AdapterControlPort_V2G.hh" +#endif +//#ifdef LibItsPki__TestSystem_HH +//#include "Pki_ports/AdapterControlPort_Pki.hh" +//#endif + +#else //_NO_SOFTLINKS_ + +#ifdef LibItsCam__TestSystem_HH +#include "AdapterControlPort_CAM.hh" +#endif +#ifdef LibItsDenm__TestSystem_HH +#include "AdapterControlPort_DENM.hh" +#endif +#ifdef LibItsIvim__TestSystem_HH +#include "AdapterControlPort_IVIM.hh" +#endif +#ifdef LibItsMapemSpatem__TestSystem_HH +#include "AdapterControlPort_MapemSpatem.hh" +#endif +#ifdef LibItsSremSsem__TestSystem_HH +#include "AdapterControlPort_SremSsem.hh" +#endif +#ifdef LibItsRtcmem__TestSystem_HH +#include "AdapterControlPort_Rtcmem.hh" +#endif +#ifdef LibItsGeoNetworking__TestSystem_HH +#include "AdapterControlPort_GN.hh" +#endif +/* +#include "AdapterControlPort_Evcsn.partH" +#include "AdapterControlPort_IVIM.partH" +#include "AdapterControlPort_MapemSpatem.partH" +#include "AdapterControlPort_SremSsem.partH" +*/ +//#include "AdapterControlPort_V2G.partH" +#endif //_NO_SOFTLINKS_ diff --git a/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.cc b/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.cc index 6dfc8e5c2ec16f94cf50a3302832f81bdee6cdef..2822ddb54648591b964f9f02fefa18a1411570f1 100644 --- a/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.cc +++ b/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.cc @@ -1,41 +1,41 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "HmiPort.hh" - -namespace ItsAutoInterop__TestSystem { - - HmiPort::HmiPort(const char *par_port_name) : HmiPort_BASE(par_port_name) {} - - HmiPort::~HmiPort() {} - - void HmiPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void HmiPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void HmiPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void HmiPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void HmiPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void HmiPort::Handle_Timeout(double time_since_last_call) {}*/ - - void HmiPort::user_map(const char * /*system_port*/) {} - - void HmiPort::user_unmap(const char * /*system_port*/) {} - - void HmiPort::user_start() {} - - void HmiPort::user_stop() {} - - void HmiPort::outgoing_send(const ItsAutoInterop__TypesAndValues::HmiInitialize & /*send_par*/) {} - -} // namespace ItsAutoInterop__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "HmiPort.hh" + +namespace ItsAutoInterop__TestSystem { + + HmiPort::HmiPort(const char *par_port_name) : HmiPort_BASE(par_port_name) {} + + HmiPort::~HmiPort() {} + + void HmiPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void HmiPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void HmiPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void HmiPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void HmiPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void HmiPort::Handle_Timeout(double time_since_last_call) {}*/ + + void HmiPort::user_map(const char * /*system_port*/) {} + + void HmiPort::user_unmap(const char * /*system_port*/) {} + + void HmiPort::user_start() {} + + void HmiPort::user_stop() {} + + void HmiPort::outgoing_send(const ItsAutoInterop__TypesAndValues::HmiInitialize & /*send_par*/) {} + +} // namespace ItsAutoInterop__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.hh b/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.hh index 5e56f75974d2f95c6fa1c1eb8cd4ae7a641509c4..2cc6f8d43120e47717e1a8a015ab81d88dd37ad5 100644 --- a/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.hh +++ b/ccsrc/Ports/LibIts_ports/AutoInterop_ports/HmiPort.hh @@ -1,44 +1,44 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef HmiPort_HH -#define HmiPort_HH - -#include "ItsAutoInterop_TestSystem.hh" -#include "ItsAutoInterop_TypesAndValues.hh" - -namespace ItsAutoInterop__TestSystem { - - class HmiPort : public HmiPort_BASE { - public: - HmiPort(const char *par_port_name = NULL); - ~HmiPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const ItsAutoInterop__TypesAndValues::HmiInitialize &send_par); - }; - -} // namespace ItsAutoInterop__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef HmiPort_HH +#define HmiPort_HH + +#include "ItsAutoInterop_TestSystem.hh" +#include "ItsAutoInterop_TypesAndValues.hh" + +namespace ItsAutoInterop__TestSystem { + + class HmiPort : public HmiPort_BASE { + public: + HmiPort(const char *par_port_name = NULL); + ~HmiPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const ItsAutoInterop__TypesAndValues::HmiInitialize &send_par); + }; + +} // namespace ItsAutoInterop__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.cc b/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.cc index 92b9a6fbc57c93e055809d62116a3d748be0aa26..6146ed7a9a9f3fb42d97bbd7176843af4ecf214d 100644 --- a/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.cc +++ b/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.cc @@ -1,87 +1,87 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "BtpPort.hh" -#include "btp_layer_factory.hh" -#include "loggers.hh" - -namespace LibItsBtp__TestSystem { - - BtpPort::BtpPort(const char *par_port_name) - : BtpPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("BtpPort::outgoing_send") {} - - BtpPort::~BtpPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void BtpPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("BtpPort::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - } - - /*void BtpPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void BtpPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void BtpPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void BtpPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void BtpPort::Handle_Timeout(double time_since_last_call) {}*/ - - void BtpPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> BtpPort::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("BtpPort::user_map: %s", it->second.c_str()); - // Setup parameters - params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless - // Create layer - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("BtpPort::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("BtpPort::user_map: No layers defined in configuration file"); - } - } - - void BtpPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> BtpPort::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void BtpPort::user_start() {} - - void BtpPort::user_stop() {} - - void BtpPort::outgoing_send(const BtpReq &send_par) { - // loggers::get_instance().log_msg(">>> BtpPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void BtpPort::receiveMsg(const LibItsBtp__TestSystem::BtpInd &p_ind, const params &p_params) { - // loggers::get_instance().log_msg(">>> BtpPort::receive_msg: ", p_ind); - - incoming_message(p_ind); - } - -} // namespace LibItsBtp__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "BtpPort.hh" +#include "btp_layer_factory.hh" +#include "loggers.hh" + +namespace LibItsBtp__TestSystem { + + BtpPort::BtpPort(const char *par_port_name) + : BtpPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("BtpPort::outgoing_send") {} + + BtpPort::~BtpPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void BtpPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("BtpPort::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + } + + /*void BtpPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void BtpPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void BtpPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void BtpPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void BtpPort::Handle_Timeout(double time_since_last_call) {}*/ + + void BtpPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> BtpPort::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("BtpPort::user_map: %s", it->second.c_str()); + // Setup parameters + params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless + // Create layer + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("BtpPort::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("BtpPort::user_map: No layers defined in configuration file"); + } + } + + void BtpPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> BtpPort::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void BtpPort::user_start() {} + + void BtpPort::user_stop() {} + + void BtpPort::outgoing_send(const LibItsBtp__TypesAndValues::BtpReq &send_par) { + // loggers::get_instance().log_msg(">>> BtpPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void BtpPort::receiveMsg(const LibItsBtp__TypesAndValues::BtpInd &p_ind, const params &p_params) { + // loggers::get_instance().log_msg(">>> BtpPort::receive_msg: ", p_ind); + + incoming_message(p_ind); + } + +} // namespace LibItsBtp__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.hh b/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.hh index 86a7b1b62f55b3b5ee82a6ee5b5fdb5428b5eb05..cb00d764ca948eeb7f8644abbc712e2774e12488 100644 --- a/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.hh +++ b/ccsrc/Ports/LibIts_ports/BTP_ports/BtpPort.hh @@ -1,53 +1,53 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef BtpPort_HH -#define BtpPort_HH - -#include "LibItsBtp_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsBtp__TestSystem { - - class BtpPort : public BtpPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - BtpPort(const char *par_port_name = NULL); - ~BtpPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const LibItsBtp__TestSystem::BtpInd &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const BtpReq &send_par); - }; - -} // namespace LibItsBtp__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef BtpPort_HH +#define BtpPort_HH + +#include "LibItsBtp_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsBtp__TestSystem { + + class BtpPort : public BtpPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + BtpPort(const char *par_port_name = NULL); + ~BtpPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const LibItsBtp__TypesAndValues::BtpInd &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsBtp__TypesAndValues::BtpReq &send_par); + }; + +} // namespace LibItsBtp__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.cc b/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.cc index 6d0534a5670c2fcad3dde5ae25f2083ab8b5a877..bcd3ceeb1e85ff79f5b8139d379da3149c14f064 100644 --- a/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.cc +++ b/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.cc @@ -1,34 +1,34 @@ -#include "UpperTesterPort_BTP.hh" -//============================================================================= -namespace LibItsBtp__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} - - UpperTesterPort::~UpperTesterPort() {} - - void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char * /*system_port*/) {} - - void UpperTesterPort::user_unmap(const char * /*system_port*/) {} - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsBtp__TypesAndValues::UtBtpInitialize & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsBtp__TypesAndValues::UtBtpTrigger & /*send_par*/) {} - -} // namespace LibItsBtp__TestSystem +#include "UpperTesterPort_BTP.hh" +//============================================================================= +namespace LibItsBtp__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} + + UpperTesterPort::~UpperTesterPort() {} + + void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char * /*system_port*/) {} + + void UpperTesterPort::user_unmap(const char * /*system_port*/) {} + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsBtp__TypesAndValues::UtBtpInitialize & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsBtp__TypesAndValues::UtBtpTrigger & /*send_par*/) {} + +} // namespace LibItsBtp__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.hh b/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.hh index 3e3014bd030a0b07499d703a05b16064f8e0e10d..79ddc505e36a4db65f0daabf3db31e9ac5237b84 100644 --- a/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.hh +++ b/ccsrc/Ports/LibIts_ports/BTP_ports/UpperTesterPort_BTP.hh @@ -1,34 +1,34 @@ -//============================================================================= -#ifndef UpperTesterPort_BTP_HH -#define UpperTesterPort_BTP_HH -#include "LibItsBtp_TestSystem.hh" -namespace LibItsBtp__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsBtp__TypesAndValues::UtBtpInitialize &send_par); - - void outgoing_send(const LibItsBtp__TypesAndValues::UtBtpTrigger &send_par); - }; - -} // namespace LibItsBtp__TestSystem -#endif +//============================================================================= +#ifndef UpperTesterPort_BTP_HH +#define UpperTesterPort_BTP_HH +#include "LibItsBtp_TestSystem.hh" +namespace LibItsBtp__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsBtp__TypesAndValues::UtBtpInitialize &send_par); + + void outgoing_send(const LibItsBtp__TypesAndValues::UtBtpTrigger &send_par); + }; + +} // namespace LibItsBtp__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/BTP_ports/module.mk b/ccsrc/Ports/LibIts_ports/BTP_ports/module.mk index c34bd790297080370672d7fb0a150e0f34422bc2..d96ef4ffa51119b7dd8701c9e68fc2ccf5928826 100644 --- a/ccsrc/Ports/LibIts_ports/BTP_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/BTP_ports/module.mk @@ -1,3 +1,3 @@ -sources := BtpPort.cc UpperTesterPort_BTP.cc -includes := . - +sources := BtpPort.cc UpperTesterPort_BTP.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.cc b/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.cc index c3cb5ccae23a3b55f19c2f9001a7a17f412e7d10..cf139722fb02fabd82388c83f1555379d4c96fd0 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.cc +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.cc @@ -1,70 +1,70 @@ -#include - -#include "loggers.hh" -#include "registration.hh" - -#include "AdapterControlPort_CAM.hh" -#include "cam_layer.hh" - -//============================================================================= -namespace LibItsCam__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - cam_layer *p = registration::get_instance().get_item(std::string("CAM")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: CAM not registered"); - } - } - -} // namespace LibItsCam__TestSystem +#include + +#include "loggers.hh" +#include "registration.hh" + +#include "AdapterControlPort_CAM.hh" +#include "cam_layer.hh" + +//============================================================================= +namespace LibItsCam__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + cam_layer *p = registration::get_instance().get_item(std::string("CAM")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: CAM not registered"); + } + } + +} // namespace LibItsCam__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.hh b/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.hh index 5c66a55cd2669e937fdc65081255f6c64f7a4458..6ecc97c4e9eb2d6fd69db4e6b214a740d10123bc 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.hh +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/AdapterControlPort_CAM.hh @@ -1,36 +1,36 @@ -#ifndef AdapterControlPort_CAM_HH -#define AdapterControlPort_CAM_HH -//============================================================================= -#include "LibItsCam_TestSystem.hh" - -namespace LibItsCam__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsCam__TestSystem - -#endif +#ifndef AdapterControlPort_CAM_HH +#define AdapterControlPort_CAM_HH +//============================================================================= +#include "LibItsCam_TestSystem.hh" + +namespace LibItsCam__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsCam__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.cc b/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.cc index 51bc556e751f9a605a0b47f8f9fc4522a33cec03..d8fa7788ceddd9a778e20f32f44c278a27c9e609 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.cc +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.cc @@ -1,88 +1,88 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "CamPort.hh" -#include "cam_layer_factory.hh" -#include "loggers.hh" - -namespace LibItsCam__TestSystem { - - CamPort::CamPort(const char *par_port_name) - : CamPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("CamPort::outgoing_send") {} - - CamPort::~CamPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void CamPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("CamPort::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - } - - /*void CamPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void CamPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void CamPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void CamPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void CamPort::Handle_Timeout(double time_since_last_call) {}*/ - - void CamPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> CamPort::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("CamPort::user_map: %s", it->second.c_str()); - // Setup parameters - params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless - // Create layer - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("CamPort::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("CamPort::user_map: No layers defined in configuration file"); - } - } - - void CamPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> CamPort::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void CamPort::user_start() {} - - void CamPort::user_stop() {} - - void CamPort::outgoing_send(const LibItsCam__TypesAndValues::CamReq &send_par) { - loggers::get_instance().log_msg(">>> CamPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - params params; - static_cast(_layer)->sendMsg(send_par, params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void CamPort::receiveMsg(const LibItsCam__TypesAndValues::CamInd &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> CamPort::receive_msg: ", p_ind); - - incoming_message(p_ind); - } - -} // namespace LibItsCam__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "CamPort.hh" +#include "cam_layer_factory.hh" +#include "loggers.hh" + +namespace LibItsCam__TestSystem { + + CamPort::CamPort(const char *par_port_name) + : CamPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("CamPort::outgoing_send") {} + + CamPort::~CamPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void CamPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("CamPort::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + } + + /*void CamPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void CamPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void CamPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void CamPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void CamPort::Handle_Timeout(double time_since_last_call) {}*/ + + void CamPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> CamPort::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("CamPort::user_map: %s", it->second.c_str()); + // Setup parameters + params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless + // Create layer + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("CamPort::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("CamPort::user_map: No layers defined in configuration file"); + } + } + + void CamPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> CamPort::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void CamPort::user_start() {} + + void CamPort::user_stop() {} + + void CamPort::outgoing_send(const LibItsCam__TypesAndValues::CamReq &send_par) { + loggers::get_instance().log_msg(">>> CamPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + params params; + static_cast(_layer)->sendMsg(send_par, params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void CamPort::receiveMsg(const LibItsCam__TypesAndValues::CamInd &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> CamPort::receive_msg: ", p_ind); + + incoming_message(p_ind); + } + +} // namespace LibItsCam__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.hh b/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.hh index 59523331d5f9504f9243292bcea9ebaa8a296057..f3583828b6d55cb46f70ff1f7bbf96b2fae6b1fe 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.hh +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/CamPort.hh @@ -1,53 +1,53 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef CamPort_HH -#define CamPort_HH - -#include "LibItsCam_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsCam__TestSystem { - - class CamPort : public CamPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - CamPort(const char *par_port_name = NULL); - ~CamPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const LibItsCam__TypesAndValues::CamInd &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCam__TypesAndValues::CamReq &send_par); - }; - -} // namespace LibItsCam__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef CamPort_HH +#define CamPort_HH + +#include "LibItsCam_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsCam__TestSystem { + + class CamPort : public CamPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + CamPort(const char *par_port_name = NULL); + ~CamPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const LibItsCam__TypesAndValues::CamInd &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCam__TypesAndValues::CamReq &send_par); + }; + +} // namespace LibItsCam__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.cc b/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.cc index 2ff55eacffd77629d8cc63d522bc38fdd8381881..1d88b4890213bbab2bc578600c1d0172afd3be9d 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.cc +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.cc @@ -1,112 +1,112 @@ -#include "uppertester_cam_layer_factory.hh" - -#include "UpperTesterPort_CAM.hh" -#include "loggers.hh" - -//============================================================================= -namespace LibItsCam__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Cam::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_Cam::UpperTesterPort_Cam"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_Cam::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Cam::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_Cam::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_Cam::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_Cam::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Cam::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort_Cam::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort_Cam::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort_Cam::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtActivatePositionTime & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtDeactivatePositionTime & /*send_par*/) {} - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_Cam::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamResults") == 0) { // TODO To be refined - incoming_message(static_cast(p_ind)); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } else { - loggers::get_instance().warning("UpperTesterPort_Cam::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); - } - } - -} // namespace LibItsCam__TestSystem +#include "uppertester_cam_layer_factory.hh" + +#include "UpperTesterPort_CAM.hh" +#include "loggers.hh" + +//============================================================================= +namespace LibItsCam__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Cam::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_Cam::UpperTesterPort_Cam"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_Cam::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Cam::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_Cam::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_Cam::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_Cam::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Cam::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort_Cam::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort_Cam::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort_Cam::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtActivatePositionTime & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsCam__TypesAndValues::UtDeactivatePositionTime & /*send_par*/) {} + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_Cam::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamResults") == 0) { // TODO To be refined + incoming_message(static_cast(p_ind)); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } else { + loggers::get_instance().warning("UpperTesterPort_Cam::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); + } + } + +} // namespace LibItsCam__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.hh b/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.hh index f3c71174341913c4843ec80a085cc1c91de53681..1afc996e501f4e1a91b907479380bf8da2e44b10 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.hh +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/UpperTesterPort_CAM.hh @@ -1,51 +1,51 @@ -#ifndef UpperTesterPort_CAM_HH -#define UpperTesterPort_CAM_HH - -#include "layer.hh" -#include "params.hh" - -//============================================================================= -#include "LibItsCam_TestSystem.hh" -namespace LibItsCam__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCam__TypesAndValues::UtCamInitialize &send_par); - - void outgoing_send(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par); - - void outgoing_send(const LibItsCam__TypesAndValues::UtCamTrigger &send_par); - - void outgoing_send(const LibItsCam__TypesAndValues::UtActivatePositionTime &send_par); - - void outgoing_send(const LibItsCam__TypesAndValues::UtDeactivatePositionTime &send_par); - }; - -} // namespace LibItsCam__TestSystem -#endif +#ifndef UpperTesterPort_CAM_HH +#define UpperTesterPort_CAM_HH + +#include "layer.hh" +#include "params.hh" + +//============================================================================= +#include "LibItsCam_TestSystem.hh" +namespace LibItsCam__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCam__TypesAndValues::UtCamInitialize &send_par); + + void outgoing_send(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par); + + void outgoing_send(const LibItsCam__TypesAndValues::UtCamTrigger &send_par); + + void outgoing_send(const LibItsCam__TypesAndValues::UtActivatePositionTime &send_par); + + void outgoing_send(const LibItsCam__TypesAndValues::UtDeactivatePositionTime &send_par); + }; + +} // namespace LibItsCam__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/CAM_ports/module.mk b/ccsrc/Ports/LibIts_ports/CAM_ports/module.mk index 45ed2a02d69214e3289c085eacb9af7f43e674ae..aab1debd4d6a59489dae157933a63be2e12eb72d 100644 --- a/ccsrc/Ports/LibIts_ports/CAM_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/CAM_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_CAM.cc CamPort.cc UpperTesterPort_CAM.cc -includes := . - +sources := AdapterControlPort_CAM.cc CamPort.cc UpperTesterPort_CAM.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.cc b/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.cc index becd2f8713f93523193be90a4b84475c56a7f4dc..072a9d95ea473b23fae5b1811ba99904b160f23a 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.cc +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.cc @@ -1,41 +1,41 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "CheckPort.hh" - -namespace LibItsDcc__TestSystem { - - CheckPort::CheckPort(const char *par_port_name) : CheckPort_BASE(par_port_name) {} - - CheckPort::~CheckPort() {} - - void CheckPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void CheckPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void CheckPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void CheckPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void CheckPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void CheckPort::Handle_Timeout(double time_since_last_call) {}*/ - - void CheckPort::user_map(const char * /*system_port*/) {} - - void CheckPort::user_unmap(const char * /*system_port*/) {} - - void CheckPort::user_start() {} - - void CheckPort::user_stop() {} - - void CheckPort::outgoing_send(const INTEGER & /*send_par*/) {} - -} // namespace LibItsDcc__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "CheckPort.hh" + +namespace LibItsDcc__TestSystem { + + CheckPort::CheckPort(const char *par_port_name) : CheckPort_BASE(par_port_name) {} + + CheckPort::~CheckPort() {} + + void CheckPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void CheckPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void CheckPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void CheckPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void CheckPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void CheckPort::Handle_Timeout(double time_since_last_call) {}*/ + + void CheckPort::user_map(const char * /*system_port*/) {} + + void CheckPort::user_unmap(const char * /*system_port*/) {} + + void CheckPort::user_start() {} + + void CheckPort::user_stop() {} + + void CheckPort::outgoing_send(const INTEGER & /*send_par*/) {} + +} // namespace LibItsDcc__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.hh b/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.hh index 3789bfdb08629e12931ce923781ce939be41d7cf..52027986a530e4f1d0ed02c9730e0f2386a48894 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.hh +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/CheckPort.hh @@ -1,43 +1,43 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef CheckPort_HH -#define CheckPort_HH - -#include "LibItsDcc_TestSystem.hh" - -namespace LibItsDcc__TestSystem { - - class CheckPort : public CheckPort_BASE { - public: - CheckPort(const char *par_port_name = NULL); - ~CheckPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const INTEGER &send_par); - }; - -} // namespace LibItsDcc__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef CheckPort_HH +#define CheckPort_HH + +#include "LibItsDcc_TestSystem.hh" + +namespace LibItsDcc__TestSystem { + + class CheckPort : public CheckPort_BASE { + public: + CheckPort(const char *par_port_name = NULL); + ~CheckPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const INTEGER &send_par); + }; + +} // namespace LibItsDcc__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.cc b/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.cc index 91f773a862c04bd090418a98437b980d3f3206bc..b89f10489c966e56ee7d8ea766ac3d4dfd429907 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.cc +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.cc @@ -1,41 +1,41 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "InPort.hh" - -namespace LibItsDcc__TestSystem { - - InPort::InPort(const char *par_port_name) : InPort_BASE(par_port_name) {} - - InPort::~InPort() {} - - void InPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void InPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void InPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void InPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void InPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void InPort::Handle_Timeout(double time_since_last_call) {}*/ - - void InPort::user_map(const char * /*system_port*/) {} - - void InPort::user_unmap(const char * /*system_port*/) {} - - void InPort::user_start() {} - - void InPort::user_stop() {} - - void InPort::outgoing_send(const LibItsDcc__TypesAndValues::InReq & /*send_par*/) {} - -} // namespace LibItsDcc__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "InPort.hh" + +namespace LibItsDcc__TestSystem { + + InPort::InPort(const char *par_port_name) : InPort_BASE(par_port_name) {} + + InPort::~InPort() {} + + void InPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void InPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void InPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void InPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void InPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void InPort::Handle_Timeout(double time_since_last_call) {}*/ + + void InPort::user_map(const char * /*system_port*/) {} + + void InPort::user_unmap(const char * /*system_port*/) {} + + void InPort::user_start() {} + + void InPort::user_stop() {} + + void InPort::outgoing_send(const LibItsDcc__TypesAndValues::InReq & /*send_par*/) {} + +} // namespace LibItsDcc__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.hh b/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.hh index acbcbfcb9b291fd1b018020113ecf027db52ac0b..91b1d389808ac04ef52f204ad75868c10534ca55 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.hh +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/InPort.hh @@ -1,43 +1,43 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef InPort_HH -#define InPort_HH - -#include "LibItsDcc_TestSystem.hh" - -namespace LibItsDcc__TestSystem { - - class InPort : public InPort_BASE { - public: - InPort(const char *par_port_name = NULL); - ~InPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsDcc__TypesAndValues::InReq &send_par); - }; - -} // namespace LibItsDcc__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef InPort_HH +#define InPort_HH + +#include "LibItsDcc_TestSystem.hh" + +namespace LibItsDcc__TestSystem { + + class InPort : public InPort_BASE { + public: + InPort(const char *par_port_name = NULL); + ~InPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsDcc__TypesAndValues::InReq &send_par); + }; + +} // namespace LibItsDcc__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.cc b/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.cc index fb1c78e6d3d0f9b7dedf65d6eb71fd49fa0da9a4..d1e95cb0dc5c452b3b49e82af76139a1260515fa 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.cc +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.cc @@ -1,39 +1,39 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "RrxPort.hh" - -namespace LibItsDcc__TestSystem { - - RrxPort::RrxPort(const char *par_port_name) : RrxPort_BASE(par_port_name) {} - - RrxPort::~RrxPort() {} - - void RrxPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void RrxPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void RrxPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void RrxPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void RrxPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void RrxPort::Handle_Timeout(double time_since_last_call) {}*/ - - void RrxPort::user_map(const char * /*system_port*/) {} - - void RrxPort::user_unmap(const char * /*system_port*/) {} - - void RrxPort::user_start() {} - - void RrxPort::user_stop() {} - -} // namespace LibItsDcc__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "RrxPort.hh" + +namespace LibItsDcc__TestSystem { + + RrxPort::RrxPort(const char *par_port_name) : RrxPort_BASE(par_port_name) {} + + RrxPort::~RrxPort() {} + + void RrxPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void RrxPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void RrxPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void RrxPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void RrxPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void RrxPort::Handle_Timeout(double time_since_last_call) {}*/ + + void RrxPort::user_map(const char * /*system_port*/) {} + + void RrxPort::user_unmap(const char * /*system_port*/) {} + + void RrxPort::user_start() {} + + void RrxPort::user_stop() {} + +} // namespace LibItsDcc__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.hh b/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.hh index cfd3b4e7aba624f359daf3d99b67b209d567b140..d704149d78e80502a4f9d28de122542434d50224 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.hh +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/RrxPort.hh @@ -1,41 +1,41 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef RrxPort_HH -#define RrxPort_HH - -#include "LibItsDcc_TestSystem.hh" - -namespace LibItsDcc__TestSystem { - - class RrxPort : public RrxPort_BASE { - public: - RrxPort(const char *par_port_name = NULL); - ~RrxPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - }; - -} // namespace LibItsDcc__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 21:19:06 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef RrxPort_HH +#define RrxPort_HH + +#include "LibItsDcc_TestSystem.hh" + +namespace LibItsDcc__TestSystem { + + class RrxPort : public RrxPort_BASE { + public: + RrxPort(const char *par_port_name = NULL); + ~RrxPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + }; + +} // namespace LibItsDcc__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.cc b/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.cc index 2742d6ab408ae2a099cebdd296983dc7cafabd0e..e2122e8b23480764d2a6e4763e74551ce762b1ab 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.cc +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.cc @@ -1,34 +1,34 @@ -#include "UpperTesterPort_DCC.hh" -//============================================================================= -namespace LibItsDcc__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} - - UpperTesterPort::~UpperTesterPort() {} - - void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char * /*system_port*/) {} - - void UpperTesterPort::user_unmap(const char * /*system_port*/) {} - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsDcc__TestSystem::UtInitialize & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsDcc__TestSystem::UtTrigger & /*send_par*/) {} - -} // namespace LibItsDcc__TestSystem +#include "UpperTesterPort_DCC.hh" +//============================================================================= +namespace LibItsDcc__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} + + UpperTesterPort::~UpperTesterPort() {} + + void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char * /*system_port*/) {} + + void UpperTesterPort::user_unmap(const char * /*system_port*/) {} + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsDcc__TestSystem::UtInitialize & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsDcc__TestSystem::UtTrigger & /*send_par*/) {} + +} // namespace LibItsDcc__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.hh b/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.hh index bde15bd40af8cb3610becfdc66f85e9d512aeada..3eac2db346f9a38609bcc06a29953c4bc484986f 100644 --- a/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.hh +++ b/ccsrc/Ports/LibIts_ports/DCC_ports/UpperTesterPort_DCC.hh @@ -1,35 +1,35 @@ -//============================================================================= -#ifndef UpperTesterPort_DCC_HH -#define UpperTesterPort_DCC_HH - -#include "LibItsDcc_TestSystem.hh" -namespace LibItsDcc__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsDcc__TestSystem::UtInitialize &send_par); - - void outgoing_send(const LibItsDcc__TestSystem::UtTrigger &send_par); - }; - -} // namespace LibItsDcc__TestSystem -#endif +//============================================================================= +#ifndef UpperTesterPort_DCC_HH +#define UpperTesterPort_DCC_HH + +#include "LibItsDcc_TestSystem.hh" +namespace LibItsDcc__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsDcc__TestSystem::UtInitialize &send_par); + + void outgoing_send(const LibItsDcc__TestSystem::UtTrigger &send_par); + }; + +} // namespace LibItsDcc__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.cc b/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.cc index 3dd9007deeec0fef981ba852234f9ee6ebb3b30b..0e145932c80a7a555d1180732b790f6d1613cfc4 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.cc +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.cc @@ -1,69 +1,69 @@ -#include - -#include "loggers.hh" -#include "registration.hh" - -#include "AdapterControlPort_DENM.hh" -#include "denm_layer.hh" -//============================================================================= -namespace LibItsDenm__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - denm_layer *p = registration::get_instance().get_item(std::string("DENM")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: %s not registered", "geoNetworkingPort"); - } - } - -} // namespace LibItsDenm__TestSystem +#include + +#include "loggers.hh" +#include "registration.hh" + +#include "AdapterControlPort_DENM.hh" +#include "denm_layer.hh" +//============================================================================= +namespace LibItsDenm__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + denm_layer *p = registration::get_instance().get_item(std::string("DENM")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: %s not registered", "geoNetworkingPort"); + } + } + +} // namespace LibItsDenm__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.hh b/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.hh index 5f09a914c8ef1c814c3d25b37185ccb598ae817d..ccc1212feb596f2b641b88d709b766c3486fe0c1 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.hh +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/AdapterControlPort_DENM.hh @@ -1,36 +1,36 @@ -//============================================================================= -#ifndef AdapterControlPort_DENM_HH -#define AdapterControlPort_DENM_HH - -#include "LibItsDenm_TestSystem.hh" - -namespace LibItsDenm__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsDenm__TestSystem -#endif +//============================================================================= +#ifndef AdapterControlPort_DENM_HH +#define AdapterControlPort_DENM_HH + +#include "LibItsDenm_TestSystem.hh" + +namespace LibItsDenm__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsDenm__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.cc b/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.cc index 7274ced02e40bc6f8b90af78bc65e13fad6b5eb7..b5266bdc51a4dfbeb4bb0b4ff9c8617ef6bb9499 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.cc +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.cc @@ -1,88 +1,88 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "DenmPort.hh" -#include "denm_layer_factory.hh" -#include "loggers.hh" - -namespace LibItsDenm__TestSystem { - - DenmPort::DenmPort(const char *par_port_name) - : DenmPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("DenmPort::outgoing_send") {} - - DenmPort::~DenmPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void DenmPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("DenmPort::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - } - - /*void DenmPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void DenmPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void DenmPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void DenmPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void DenmPort::Handle_Timeout(double time_since_last_call) {}*/ - - void DenmPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> DenmPort::user_map: %s", system_port); - // Build layer stack - std::map::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("DenmPort::user_map: %s", it->second.c_str()); - // Setup parameters - params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless - // Create layer - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("DenmPort::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("DenmPort::user_map: No layers defined in configuration file"); - } - } - - void DenmPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> DenmPort::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void DenmPort::user_start() {} - - void DenmPort::user_stop() {} - - void DenmPort::outgoing_send(const DenmReq &send_par) { - // loggers::get_instance().log_msg(">>> DenmPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - params params; - static_cast(_layer)->sendMsg(send_par, params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void DenmPort::receiveMsg(const LibItsDenm__TestSystem::DenmInd &p_ind, const params &p_params) { - // loggers::get_instance().log_msg(">>> DenmPort::receive_msg: ", p_ind); - - incoming_message(p_ind); - } - -} // namespace LibItsDenm__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "DenmPort.hh" +#include "denm_layer_factory.hh" +#include "loggers.hh" + +namespace LibItsDenm__TestSystem { + + DenmPort::DenmPort(const char *par_port_name) + : DenmPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("DenmPort::outgoing_send") {} + + DenmPort::~DenmPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void DenmPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("DenmPort::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + } + + /*void DenmPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void DenmPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void DenmPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void DenmPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void DenmPort::Handle_Timeout(double time_since_last_call) {}*/ + + void DenmPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> DenmPort::user_map: %s", system_port); + // Build layer stack + std::map::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("DenmPort::user_map: %s", it->second.c_str()); + // Setup parameters + params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless + // Create layer + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("DenmPort::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("DenmPort::user_map: No layers defined in configuration file"); + } + } + + void DenmPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> DenmPort::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void DenmPort::user_start() {} + + void DenmPort::user_stop() {} + + void DenmPort::outgoing_send(const LibItsDenm__TypesAndValues::DenmReq &send_par) { + // loggers::get_instance().log_msg(">>> DenmPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + params params; + static_cast(_layer)->sendMsg(send_par, params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void DenmPort::receiveMsg(const LibItsDenm__TypesAndValues::DenmInd &p_ind, const params &p_params) { + // loggers::get_instance().log_msg(">>> DenmPort::receive_msg: ", p_ind); + + incoming_message(p_ind); + } + +} // namespace LibItsDenm__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.hh b/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.hh index 489d1093d49db4367575e979583a45de36ab8a3a..8d45dbd0624f6a70008f7161e2cd71b9ab1f8bd9 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.hh +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/DenmPort.hh @@ -1,53 +1,53 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef DenmPort_HH -#define DenmPort_HH - -#include "LibItsDenm_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsDenm__TestSystem { - - class DenmPort : public DenmPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - DenmPort(const char *par_port_name = NULL); - ~DenmPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const LibItsDenm__TestSystem::DenmInd &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const DenmReq &send_par); - }; - -} // namespace LibItsDenm__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef DenmPort_HH +#define DenmPort_HH + +#include "LibItsDenm_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsDenm__TestSystem { + + class DenmPort : public DenmPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + DenmPort(const char *par_port_name = NULL); + ~DenmPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const LibItsDenm__TypesAndValues::DenmInd &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsDenm__TypesAndValues::DenmReq &send_par); + }; + +} // namespace LibItsDenm__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.cc b/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.cc index d45660d3c5b8f9c7733109515e5a58f690e6594b..d24aa72a3327b8793ba4df1a2816d42d9250421d 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.cc +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.cc @@ -1,134 +1,134 @@ -#include "uppertester_denm_layer_factory.hh" - -#include "UpperTesterPort_DENM.hh" -#include "loggers.hh" -//============================================================================= -namespace LibItsDenm__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Denm::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_Denm::UpperTesterPort_Denm"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_Denm::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort_Denm::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort_Denm::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Denm::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_Denm::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_Denm::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_Denm::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Denm::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_Denm::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmResults") == 0) { // TODO To be refined - incoming_message(static_cast(p_ind)); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } else { - loggers::get_instance().warning("UpperTesterPort_Denm::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); - } - } - -} // namespace LibItsDenm__TestSystem +#include "uppertester_denm_layer_factory.hh" + +#include "UpperTesterPort_DENM.hh" +#include "loggers.hh" +//============================================================================= +namespace LibItsDenm__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Denm::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_Denm::UpperTesterPort_Denm"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_Denm::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort_Denm::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort_Denm::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Denm::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_Denm::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_Denm::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_Denm::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Denm::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_Denm::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmResults") == 0) { // TODO To be refined + incoming_message(static_cast(p_ind)); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } else { + loggers::get_instance().warning("UpperTesterPort_Denm::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); + } + } + +} // namespace LibItsDenm__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.hh b/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.hh index 0c073f676ec8cfe0a3076a24cd83978e9f02277d..d4f95edc395f7790fa6a05eb4b75031be25c331a 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.hh +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/UpperTesterPort_DENM.hh @@ -1,53 +1,53 @@ -#ifndef UpperTesterPort_DENM_HH -#define UpperTesterPort_DENM_HH - -#include "layer.hh" -#include "params.hh" - -//============================================================================= -#include "LibItsDenm_TestSystem.hh" -namespace LibItsDenm__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par); - - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par); - - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par); - - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par); - - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par); - - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par); - }; - -} // namespace LibItsDenm__TestSystem -#endif +#ifndef UpperTesterPort_DENM_HH +#define UpperTesterPort_DENM_HH + +#include "layer.hh" +#include "params.hh" + +//============================================================================= +#include "LibItsDenm_TestSystem.hh" +namespace LibItsDenm__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par); + + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par); + + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par); + + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par); + + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par); + + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par); + }; + +} // namespace LibItsDenm__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/DENM_ports/module.mk b/ccsrc/Ports/LibIts_ports/DENM_ports/module.mk index 4cb04ae0d1932448029f6def26baf6ab242655cc..b17fd044ff801f029c72f9501ead7d819a541fbf 100644 --- a/ccsrc/Ports/LibIts_ports/DENM_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/DENM_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_DENM.cc DenmPort.cc UpperTesterPort_DENM.cc -includes := . - +sources := AdapterControlPort_DENM.cc DenmPort.cc UpperTesterPort_DENM.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.cc b/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.cc index 71fb589966a29303d9c99e2f1295cd4ed906ad1b..da79162e61774cb7ea51e9322c82123492a57890 100644 --- a/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.cc +++ b/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.cc @@ -1,34 +1,34 @@ -#include "AdapterControlPort_EVCSN.hh" -//============================================================================= -namespace LibItsEvcsn__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive & /*send_par*/) {} - -} // namespace LibItsEvcsn__TestSystem +#include "AdapterControlPort_EVCSN.hh" +//============================================================================= +namespace LibItsEvcsn__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive & /*send_par*/) {} + +} // namespace LibItsEvcsn__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.hh b/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.hh index 528127af874c00369ce5c7f6b35385387260a26b..9ade44bdc5fd99fca2d9724b2543b3fc11e5ac29 100644 --- a/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.hh +++ b/ccsrc/Ports/LibIts_ports/EVCSN_ports/AdapterControlPort_EVCSN.hh @@ -1,36 +1,36 @@ -#ifndef AdapterControlPort_EVCSN_HH -#define AdapterControlPort_EVCSN_HH - -//============================================================================= -#include "LibItsEvcsn_TestSystem.hh" - -namespace LibItsEvcsn__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsEvcsn__TestSystem -#endif +#ifndef AdapterControlPort_EVCSN_HH +#define AdapterControlPort_EVCSN_HH + +//============================================================================= +#include "LibItsEvcsn_TestSystem.hh" + +namespace LibItsEvcsn__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsEvcsn__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.cc b/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.cc index 0cf2e601133c1985afd599a0aa4a5ac891c35700..782e922daffb33b36f66a393b47f42fb520f80e5 100644 --- a/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.cc +++ b/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.cc @@ -1,41 +1,41 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "EvcsnPort.hh" - -namespace LibItsEvcsn__TestSystem { - - EvcsnPort::EvcsnPort(const char *par_port_name) : EvcsnPort_BASE(par_port_name) {} - - EvcsnPort::~EvcsnPort() {} - - void EvcsnPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void EvcsnPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void EvcsnPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void EvcsnPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void EvcsnPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void EvcsnPort::Handle_Timeout(double time_since_last_call) {}*/ - - void EvcsnPort::user_map(const char * /*system_port*/) {} - - void EvcsnPort::user_unmap(const char * /*system_port*/) {} - - void EvcsnPort::user_start() {} - - void EvcsnPort::user_stop() {} - - void EvcsnPort::outgoing_send(const EvcsnReq & /*send_par*/) {} - -} // namespace LibItsEvcsn__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "EvcsnPort.hh" + +namespace LibItsEvcsn__TestSystem { + + EvcsnPort::EvcsnPort(const char *par_port_name) : EvcsnPort_BASE(par_port_name) {} + + EvcsnPort::~EvcsnPort() {} + + void EvcsnPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void EvcsnPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void EvcsnPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void EvcsnPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void EvcsnPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void EvcsnPort::Handle_Timeout(double time_since_last_call) {}*/ + + void EvcsnPort::user_map(const char * /*system_port*/) {} + + void EvcsnPort::user_unmap(const char * /*system_port*/) {} + + void EvcsnPort::user_start() {} + + void EvcsnPort::user_stop() {} + + void EvcsnPort::outgoing_send(const EvcsnReq & /*send_par*/) {} + +} // namespace LibItsEvcsn__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.hh b/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.hh index 440f7cbb8dc1e0813663100a8e0388eaa8faa23b..a9ad6422b75acefa1f33bc71d024b7fcae6ba11c 100644 --- a/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.hh +++ b/ccsrc/Ports/LibIts_ports/EVCSN_ports/EvcsnPort.hh @@ -1,43 +1,43 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef EvcsnPort_HH -#define EvcsnPort_HH - -#include "LibItsEvcsn_TestSystem.hh" - -namespace LibItsEvcsn__TestSystem { - - class EvcsnPort : public EvcsnPort_BASE { - public: - EvcsnPort(const char *par_port_name = NULL); - ~EvcsnPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const EvcsnReq &send_par); - }; - -} // namespace LibItsEvcsn__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Fri Aug 14 16:32:05 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef EvcsnPort_HH +#define EvcsnPort_HH + +#include "LibItsEvcsn_TestSystem.hh" + +namespace LibItsEvcsn__TestSystem { + + class EvcsnPort : public EvcsnPort_BASE { + public: + EvcsnPort(const char *par_port_name = NULL); + ~EvcsnPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const EvcsnReq &send_par); + }; + +} // namespace LibItsEvcsn__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.cc b/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.cc index 449b054464c9980b8a5bfc59e90346897058b083..27cd5f868503afb25d1d5e5592257f0a91c64f10 100644 --- a/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.cc +++ b/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.cc @@ -1,40 +1,40 @@ -#include "UpperTesterPort_EVCSN.hh" -//============================================================================= -namespace LibItsEvcsn__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} - - UpperTesterPort::~UpperTesterPort() {} - - void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char * /*system_port*/) {} - - void UpperTesterPort::user_unmap(const char * /*system_port*/) {} - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtInitialize & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsEvcsn__TypesAndValues::UtEvcsnTrigger & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtChangePosition & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtActivatePositionTime & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtDeactivatePositionTime & /*send_par*/) {} - -} // namespace LibItsEvcsn__TestSystem +#include "UpperTesterPort_EVCSN.hh" +//============================================================================= +namespace LibItsEvcsn__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} + + UpperTesterPort::~UpperTesterPort() {} + + void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char * /*system_port*/) {} + + void UpperTesterPort::user_unmap(const char * /*system_port*/) {} + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtInitialize & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsEvcsn__TypesAndValues::UtEvcsnTrigger & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtChangePosition & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtActivatePositionTime & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsCommon__TypesAndValues::UtDeactivatePositionTime & /*send_par*/) {} + +} // namespace LibItsEvcsn__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.hh b/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.hh index 9af777815402d6d8536a6676d5137e768fad1d5e..3b04db9957f78c5b68936785c9842d250f15a297 100644 --- a/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.hh +++ b/ccsrc/Ports/LibIts_ports/EVCSN_ports/UpperTesterPort_EVCSN.hh @@ -1,41 +1,41 @@ -#ifndef UpperTesterPort_EVCSN_HH -#define UpperTesterPort_EVCSN_HH - -//============================================================================= -#include "LibItsEvcsn_TestSystem.hh" -namespace LibItsEvcsn__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::UtInitialize &send_par); - - void outgoing_send(const LibItsEvcsn__TypesAndValues::UtEvcsnTrigger &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::UtChangePosition &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::UtActivatePositionTime &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::UtDeactivatePositionTime &send_par); - }; - -} // namespace LibItsEvcsn__TestSystem -#endif +#ifndef UpperTesterPort_EVCSN_HH +#define UpperTesterPort_EVCSN_HH + +//============================================================================= +#include "LibItsEvcsn_TestSystem.hh" +namespace LibItsEvcsn__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::UtInitialize &send_par); + + void outgoing_send(const LibItsEvcsn__TypesAndValues::UtEvcsnTrigger &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::UtChangePosition &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::UtActivatePositionTime &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::UtDeactivatePositionTime &send_par); + }; + +} // namespace LibItsEvcsn__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.cc b/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.cc index 6ad577c2996d53dce9d8e099bd7bec0311bedab6..f18fed6e624e36d0bf3ba4c694cf85bb4f02b375 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.cc +++ b/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.cc @@ -1,124 +1,124 @@ -#include - -#include "loggers.hh" -#include "registration.hh" - -#include "AdapterControlPort_GN.hh" -#include "geonetworking_layer.hh" -//============================================================================= -namespace LibItsGeoNetworking__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name), _params() { - loggers::get_instance().log("AdapterControlPort::AdapterControlPort"); - } - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("AdapterControlPort::set_parameter: %s=%s", parameter_name, parameter_value); - } - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_map: %s", system_port); } - - void AdapterControlPort::user_unmap(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_unmap: %s", system_port); } - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::AcGnPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - geonetworking_layer *p = registration::get_instance().get_item(std::string("GN")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsGeoNetworking__TypesAndValues::AcGnResponse response; - response.failure() = LibItsGeoNetworking__TypesAndValues::AcGnResponseFailure(BOOLEAN(false)); - if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_startBeaconing)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Start beaconing"); - p->start_beaconing(send_par.startBeaconing().beaconPacket()); - // No response - return; - } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_stopBeaconing)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Stop beaconing"); - p->stop_beaconing(); - // No response - return; - } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_getLongPosVector)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Get LongPosVector"); - const LibItsGeoNetworking__TypesAndValues::LongPosVector *lpv = p->get_lpv(send_par.getLongPosVector().gnAddress()); - loggers::get_instance().log("AdapterControlPort::outgoing_send: Return value: %p", lpv); - if (lpv == nullptr) { - response.failure() = LibItsGeoNetworking__TypesAndValues::AcGnResponseFailure(BOOLEAN(true)); - } else { - response.getLongPosVector() = *lpv; - } - } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_startPassBeaconing)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Start pass beaconing"); - p->start_pass_beaconing(send_par.startPassBeaconing().beaconHeader()); - // No response - return; - } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_stopPassBeaconing)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Stop pass beaconing"); - p->stop_pass_beaconing(); - // No response - return; - } else { - response.failure() = LibItsGeoNetworking__TypesAndValues::AcGnResponseFailure(BOOLEAN(true)); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: %s not registered", "geoNetworkingPort"); - } - } - - void AdapterControlPort::outgoing_send(const LibItsIpv6OverGeoNetworking__TypesAndValues::AcGn6Primitive & /*send_par*/) {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - geonetworking_layer *p = registration::get_instance().get_item(std::string("GN")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: %s not registered", "geoNetworkingPort"); - } - } - -} // namespace LibItsGeoNetworking__TestSystem +#include + +#include "loggers.hh" +#include "registration.hh" + +#include "AdapterControlPort_GN.hh" +#include "geonetworking_layer.hh" +//============================================================================= +namespace LibItsGeoNetworking__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name), _params() { + loggers::get_instance().log("AdapterControlPort::AdapterControlPort"); + } + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("AdapterControlPort::set_parameter: %s=%s", parameter_name, parameter_value); + } + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_map: %s", system_port); } + + void AdapterControlPort::user_unmap(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_unmap: %s", system_port); } + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::AcGnPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + geonetworking_layer *p = registration::get_instance().get_item(std::string("GN")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsGeoNetworking__TypesAndValues::AcGnResponse response; + response.failure() = LibItsGeoNetworking__TypesAndValues::AcGnResponseFailure(BOOLEAN(false)); + if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_startBeaconing)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Start beaconing"); + p->start_beaconing(send_par.startBeaconing().beaconPacket()); + // No response + return; + } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_stopBeaconing)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Stop beaconing"); + p->stop_beaconing(); + // No response + return; + } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_getLongPosVector)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Get LongPosVector"); + const LibItsGeoNetworking__TypesAndValues::LongPosVector *lpv = p->get_lpv(send_par.getLongPosVector().gnAddress()); + loggers::get_instance().log("AdapterControlPort::outgoing_send: Return value: %p", lpv); + if (lpv == nullptr) { + response.failure() = LibItsGeoNetworking__TypesAndValues::AcGnResponseFailure(BOOLEAN(true)); + } else { + response.getLongPosVector() = *lpv; + } + } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_startPassBeaconing)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Start pass beaconing"); + p->start_pass_beaconing(send_par.startPassBeaconing().beaconHeader()); + // No response + return; + } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::AcGnPrimitive::ALT_stopPassBeaconing)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Stop pass beaconing"); + p->stop_pass_beaconing(); + // No response + return; + } else { + response.failure() = LibItsGeoNetworking__TypesAndValues::AcGnResponseFailure(BOOLEAN(true)); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: %s not registered", "geoNetworkingPort"); + } + } + + void AdapterControlPort::outgoing_send(const LibItsIpv6OverGeoNetworking__TypesAndValues::AcGn6Primitive & /*send_par*/) {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + geonetworking_layer *p = registration::get_instance().get_item(std::string("GN")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: %s not registered", "geoNetworkingPort"); + } + } + +} // namespace LibItsGeoNetworking__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.hh b/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.hh index 86f2cb364851aab11b95e598264dbadeba74010e..b2956a87291d56d55a8673ab5b84cb3259192417 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.hh +++ b/ccsrc/Ports/LibIts_ports/GN_ports/AdapterControlPort_GN.hh @@ -1,44 +1,44 @@ -#ifndef AdapterControlPort_GN_HH -#define AdapterControlPort_GN_HH - -//============================================================================= -#include "LibItsGeoNetworking_TestSystem.hh" - -#include "params.hh" - -namespace LibItsGeoNetworking__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - params _params; - - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::AcGnPrimitive &send_par); - - void outgoing_send(const LibItsIpv6OverGeoNetworking__TypesAndValues::AcGn6Primitive &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsGeoNetworking__TestSystem -#endif +#ifndef AdapterControlPort_GN_HH +#define AdapterControlPort_GN_HH + +//============================================================================= +#include "LibItsGeoNetworking_TestSystem.hh" + +#include "params.hh" + +namespace LibItsGeoNetworking__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + params _params; + + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::AcGnPrimitive &send_par); + + void outgoing_send(const LibItsIpv6OverGeoNetworking__TypesAndValues::AcGn6Primitive &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsGeoNetworking__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.cc b/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.cc index 5e3718cea99c997f20a2ee131a440e1e5f5535e8..c146944268255f686fbc1962e3c70598a0c97959 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.cc +++ b/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.cc @@ -1,99 +1,99 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sat Aug 15 22:33:04 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "GeoNetworkingPort.hh" -#include "geonetworking_layer_factory.hh" -#include "loggers.hh" - -namespace LibItsGeoNetworking__TestSystem { - - GeoNetworkingPort::GeoNetworkingPort(const char *par_port_name) - : GeoNetworkingPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(nullptr), _time_key("GeoNetworkingPort::outgoing_send") { - // Nothing to do - } // End of constructor - - GeoNetworkingPort::~GeoNetworkingPort() { - loggers::get_instance().log(">>> GeoNetworkingPort::~GeoNetworkingPort"); - - if (_layer != nullptr) { - delete _layer; - } - } // End of destructor - - void GeoNetworkingPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("GeoNetworkingPort::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - } - - /*void GeoNetworkingPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void GeoNetworkingPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void GeoNetworkingPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void GeoNetworkingPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void GeoNetworkingPort::Handle_Timeout(double time_since_last_call) {}*/ - - void GeoNetworkingPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> GeoNetworkingPort::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("GeoNetworkingPort::user_map: %s", it->second.c_str()); - // Setup parameters - params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless - // Create layer - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == nullptr) { - loggers::get_instance().error("GeoNetworkingPort::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - - } else { - loggers::get_instance().error("GeoNetworkingPort::user_map: No layers defined in configuration file"); - } - } // End of user_map method - - void GeoNetworkingPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> GeoNetworkingPort::user_unmap: %s", system_port); - - // Reset layers - if (_layer != nullptr) { - delete _layer; - _layer = nullptr; - } - } // End of user_unmap method - - void GeoNetworkingPort::user_start() { loggers::get_instance().log(">>> GeoNetworkingPort::user_start"); } // End of user_start method - - void GeoNetworkingPort::user_stop() { loggers::get_instance().log(">>> GeoNetworkingPort::user_stop"); } // End of user_stop method - - void GeoNetworkingPort::outgoing_send(const GeoNetworkingReq &send_par) { - loggers::get_instance().log_msg(">>> GeoNetworkingPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - params params; - static_cast(_layer)->sendMsg(send_par, params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void GeoNetworkingPort::receiveMsg(const LibItsGeoNetworking__TestSystem::GeoNetworkingInd &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> GeoNetworkingPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - -} // namespace LibItsGeoNetworking__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sat Aug 15 22:33:04 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "GeoNetworkingPort.hh" +#include "geonetworking_layer_factory.hh" +#include "loggers.hh" + +namespace LibItsGeoNetworking__TestSystem { + + GeoNetworkingPort::GeoNetworkingPort(const char *par_port_name) + : GeoNetworkingPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(nullptr), _time_key("GeoNetworkingPort::outgoing_send") { + // Nothing to do + } // End of constructor + + GeoNetworkingPort::~GeoNetworkingPort() { + loggers::get_instance().log(">>> GeoNetworkingPort::~GeoNetworkingPort"); + + if (_layer != nullptr) { + delete _layer; + } + } // End of destructor + + void GeoNetworkingPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("GeoNetworkingPort::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + } + + /*void GeoNetworkingPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void GeoNetworkingPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void GeoNetworkingPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void GeoNetworkingPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void GeoNetworkingPort::Handle_Timeout(double time_since_last_call) {}*/ + + void GeoNetworkingPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> GeoNetworkingPort::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("GeoNetworkingPort::user_map: %s", it->second.c_str()); + // Setup parameters + params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless + // Create layer + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == nullptr) { + loggers::get_instance().error("GeoNetworkingPort::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + + } else { + loggers::get_instance().error("GeoNetworkingPort::user_map: No layers defined in configuration file"); + } + } // End of user_map method + + void GeoNetworkingPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> GeoNetworkingPort::user_unmap: %s", system_port); + + // Reset layers + if (_layer != nullptr) { + delete _layer; + _layer = nullptr; + } + } // End of user_unmap method + + void GeoNetworkingPort::user_start() { loggers::get_instance().log(">>> GeoNetworkingPort::user_start"); } // End of user_start method + + void GeoNetworkingPort::user_stop() { loggers::get_instance().log(">>> GeoNetworkingPort::user_stop"); } // End of user_stop method + + void GeoNetworkingPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingReq &send_par) { + loggers::get_instance().log_msg(">>> GeoNetworkingPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + params params; + static_cast(_layer)->sendMsg(send_par, params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void GeoNetworkingPort::receiveMsg(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> GeoNetworkingPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + +} // namespace LibItsGeoNetworking__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.hh b/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.hh index 6a875fd083b6af600ba378a2015739fb8cbcd777..10dca9474698310c9e6bb9cc0afe8d4f47062191 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.hh +++ b/ccsrc/Ports/LibIts_ports/GN_ports/GeoNetworkingPort.hh @@ -1,50 +1,50 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sat Aug 15 22:33:04 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#pragma once - -#include "LibItsGeoNetworking_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsGeoNetworking__TestSystem { - - class GeoNetworkingPort : public GeoNetworkingPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - GeoNetworkingPort(const char *par_port_name = NULL); - ~GeoNetworkingPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const LibItsGeoNetworking__TestSystem::GeoNetworkingInd &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const GeoNetworkingReq &send_par); - }; - -} // namespace LibItsGeoNetworking__TestSystem +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sat Aug 15 22:33:04 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#pragma once + +#include "LibItsGeoNetworking_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsGeoNetworking__TestSystem { + + class GeoNetworkingPort : public GeoNetworkingPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + GeoNetworkingPort(const char *par_port_name = NULL); + ~GeoNetworkingPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + void receiveMsg(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingReq &send_par); + }; + +} // namespace LibItsGeoNetworking__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.cc b/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.cc index 1cc6b2150b72c86c6ee269c42864ff480eebcbac..69bfcec1a4110362831bc7d14bb05802ed65eeda 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.cc +++ b/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.cc @@ -1,116 +1,116 @@ -#include "uppertester_geonetworking_factory.hh" - -#include "UpperTesterPort_GN.hh" -#include "loggers.hh" -//============================================================================= -namespace LibItsGeoNetworking__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Gn::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_Gn::UpperTesterPort_Gn"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_Gn::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Gn::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_Gn::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_Gn::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_Gn::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Gn::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_Gn::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnResults") == 0) { // TODO To be refined - incoming_message((LibItsGeoNetworking__TypesAndValues::UtGnResults &)p_ind); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } else { - loggers::get_instance().warning("UpperTesterPort_Gn::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); - } - } - -} // namespace LibItsGeoNetworking__TestSystem +#include "uppertester_geonetworking_factory.hh" + +#include "UpperTesterPort_GN.hh" +#include "loggers.hh" +//============================================================================= +namespace LibItsGeoNetworking__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Gn::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_Gn::UpperTesterPort_Gn"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_Gn::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Gn::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_Gn::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_Gn::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_Gn::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Gn::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_Gn::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnResults") == 0) { // TODO To be refined + incoming_message((LibItsGeoNetworking__TypesAndValues::UtGnResults &)p_ind); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } else { + loggers::get_instance().warning("UpperTesterPort_Gn::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); + } + } + +} // namespace LibItsGeoNetworking__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.hh b/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.hh index e479f1ff110bf57c362ec94b41dee047f6295e1b..a6d9b80a77674b41693b900d9855f8b183db0a92 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.hh +++ b/ccsrc/Ports/LibIts_ports/GN_ports/UpperTesterPort_GN.hh @@ -1,48 +1,48 @@ -#ifndef UpperTesterPort_GN_HH -#define UpperTesterPort_GN_HH -#include "layer.hh" -#include "params.hh" - -//============================================================================= -#include "LibItsGeoNetworking_TestSystem.hh" -namespace LibItsGeoNetworking__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par); - - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par); - - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par); - - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par); - }; - -} // namespace LibItsGeoNetworking__TestSystem -#endif +#ifndef UpperTesterPort_GN_HH +#define UpperTesterPort_GN_HH +#include "layer.hh" +#include "params.hh" + +//============================================================================= +#include "LibItsGeoNetworking_TestSystem.hh" +namespace LibItsGeoNetworking__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par); + + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par); + + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par); + + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par); + }; + +} // namespace LibItsGeoNetworking__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/GN_ports/module.mk b/ccsrc/Ports/LibIts_ports/GN_ports/module.mk index b135587f4c8f7eaa91a5dc3a40edfe2d9d8d066d..c7a95dfbdd2e0cdf0d472ef091cf3e7906a64ae9 100644 --- a/ccsrc/Ports/LibIts_ports/GN_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/GN_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_GN.cc GeoNetworkingPort.cc UpperTesterPort_GN.cc -includes := . - +sources := AdapterControlPort_GN.cc GeoNetworkingPort.cc UpperTesterPort_GN.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.cc b/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.cc index 2f1d34728655ff50872ef718f027ee70fae7b384..d28e93ae8e9b6cb344135fe94e9d0be9c2b00d96 100644 --- a/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.cc +++ b/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.cc @@ -1,92 +1,92 @@ -#include "HttpPort.hh" -#include "http_layer_factory.hh" -#include "loggers.hh" - -#include "LibItsHttp_TypesAndValues.hh" - -namespace LibItsHttp__TestSystem { - - HttpPort::HttpPort(const char *par_port_name) - : HttpPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(nullptr), _time_key("HttpPort::outgoing_send") { - // Nothing to do - } // End of constructor - - HttpPort::~HttpPort() { - loggers::get_instance().log(">>> HttpPort::~HttpPort"); - - if (_layer != nullptr) { - delete _layer; - } - } // End of destructor - - void HttpPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("HttpPort::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - } - - /*void HttpPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void HttpPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void HttpPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void HttpPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void HttpPort::Handle_Timeout(double time_since_last_call) {}*/ - - void HttpPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> HttpPort::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("HttpPort::user_map: %s", it->second.c_str()); - // Setup parameters - params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless - // Create layer - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == nullptr) { - loggers::get_instance().error("HttpPort::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - - } else { - loggers::get_instance().error("HttpPort::user_map: No layers defined in configuration file"); - } - } // End of user_map method - - void HttpPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> HttpPort::user_unmap: %s", system_port); - - // Reset layers - if (_layer != nullptr) { - delete _layer; - _layer = nullptr; - } - } // End of user_unmap method - - void HttpPort::user_start() { loggers::get_instance().log(">>> HttpPort::user_start"); } // End of user_start method - - void HttpPort::user_stop() { loggers::get_instance().log(">>> HttpPort::user_stop"); } // End of user_stop method - - void HttpPort::outgoing_send(const LibItsHttp__TypesAndValues::HttpMessage &send_par) { - loggers::get_instance().log_msg(">>> HttpPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - params params; - static_cast(_layer)->sendMsg(send_par, params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void HttpPort::receiveMsg(const LibItsHttp__TypesAndValues::HttpMessage &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> HttpPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - -} // namespace LibItsHttp__TestSystem +#include "HttpPort.hh" +#include "http_layer_factory.hh" +#include "loggers.hh" + +#include "LibItsHttp_TypesAndValues.hh" + +namespace LibItsHttp__TestSystem { + + HttpPort::HttpPort(const char *par_port_name) + : HttpPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(nullptr), _time_key("HttpPort::outgoing_send") { + // Nothing to do + } // End of constructor + + HttpPort::~HttpPort() { + loggers::get_instance().log(">>> HttpPort::~HttpPort"); + + if (_layer != nullptr) { + delete _layer; + } + } // End of destructor + + void HttpPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("HttpPort::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + } + + /*void HttpPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void HttpPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void HttpPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void HttpPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void HttpPort::Handle_Timeout(double time_since_last_call) {}*/ + + void HttpPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> HttpPort::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("HttpPort::user_map: %s", it->second.c_str()); + // Setup parameters + params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless + // Create layer + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == nullptr) { + loggers::get_instance().error("HttpPort::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + + } else { + loggers::get_instance().error("HttpPort::user_map: No layers defined in configuration file"); + } + } // End of user_map method + + void HttpPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> HttpPort::user_unmap: %s", system_port); + + // Reset layers + if (_layer != nullptr) { + delete _layer; + _layer = nullptr; + } + } // End of user_unmap method + + void HttpPort::user_start() { loggers::get_instance().log(">>> HttpPort::user_start"); } // End of user_start method + + void HttpPort::user_stop() { loggers::get_instance().log(">>> HttpPort::user_stop"); } // End of user_stop method + + void HttpPort::outgoing_send(const LibItsHttp__TypesAndValues::HttpMessage &send_par) { + loggers::get_instance().log_msg(">>> HttpPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + params params; + static_cast(_layer)->sendMsg(send_par, params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void HttpPort::receiveMsg(const LibItsHttp__TypesAndValues::HttpMessage &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> HttpPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + +} // namespace LibItsHttp__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.hh b/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.hh index 6036174457d1d7e502ba296c0b15f4fdd96c1c26..48024dda2e61231fae341d819e7de5d607e57970 100644 --- a/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.hh +++ b/ccsrc/Ports/LibIts_ports/Http_ports/HttpPort.hh @@ -1,46 +1,46 @@ -#pragma once - -#include "LibItsHttp_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsHttp__TypesAndValues { - class HttpMessage; -} - -namespace LibItsHttp__TestSystem { - - class HttpPort : public HttpPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - HttpPort(const char *par_port_name); - ~HttpPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const LibItsHttp__TypesAndValues::HttpMessage &p_ind, const params &p_params); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - protected: - void outgoing_send(const LibItsHttp__TypesAndValues::HttpMessage &send_par); - }; // End of class HttpPort - -} // namespace LibItsHttp__TestSystem +#pragma once + +#include "LibItsHttp_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsHttp__TypesAndValues { + class HttpMessage; +} + +namespace LibItsHttp__TestSystem { + + class HttpPort : public HttpPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + HttpPort(const char *par_port_name); + ~HttpPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + void receiveMsg(const LibItsHttp__TypesAndValues::HttpMessage &p_ind, const params &p_params); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + protected: + void outgoing_send(const LibItsHttp__TypesAndValues::HttpMessage &send_par); + }; // End of class HttpPort + +} // namespace LibItsHttp__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Http_ports/module.mk b/ccsrc/Ports/LibIts_ports/Http_ports/module.mk index ac4f8ac5142a335ac5ac398774950fdb2e1cddb3..bc9fb8a0240f3ad968f691d580ed907692e1ad4f 100644 --- a/ccsrc/Ports/LibIts_ports/Http_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/Http_ports/module.mk @@ -1,3 +1,3 @@ -sources := HttpPort.cc -includes := . - +sources := HttpPort.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.cc b/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.cc index b32dd7fc79566b9ad7d4d6dd9d51d0034e92facb..6cc3789f05648372c3cd09bcdadd6f8dff4042ab 100644 --- a/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.cc +++ b/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.cc @@ -1,41 +1,41 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 09:18:30 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "IPv6OverGeoNetworkingPort.hh" - -namespace LibItsIpv6OverGeoNetworking__TestSystem { - - IPv6OverGeoNetworkingPort::IPv6OverGeoNetworkingPort(const char *par_port_name) : IPv6OverGeoNetworkingPort_BASE(par_port_name) {} - - IPv6OverGeoNetworkingPort::~IPv6OverGeoNetworkingPort() {} - - void IPv6OverGeoNetworkingPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void IPv6OverGeoNetworkingPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void IPv6OverGeoNetworkingPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void IPv6OverGeoNetworkingPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void IPv6OverGeoNetworkingPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void IPv6OverGeoNetworkingPort::Handle_Timeout(double time_since_last_call) {}*/ - - void IPv6OverGeoNetworkingPort::user_map(const char * /*system_port*/) {} - - void IPv6OverGeoNetworkingPort::user_unmap(const char * /*system_port*/) {} - - void IPv6OverGeoNetworkingPort::user_start() {} - - void IPv6OverGeoNetworkingPort::user_stop() {} - - void IPv6OverGeoNetworkingPort::outgoing_send(const IPv6OverGeoNetworkingReq & /*send_par*/) {} - -} // namespace LibItsIpv6OverGeoNetworking__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 09:18:30 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "IPv6OverGeoNetworkingPort.hh" + +namespace LibItsIpv6OverGeoNetworking__TestSystem { + + IPv6OverGeoNetworkingPort::IPv6OverGeoNetworkingPort(const char *par_port_name) : IPv6OverGeoNetworkingPort_BASE(par_port_name) {} + + IPv6OverGeoNetworkingPort::~IPv6OverGeoNetworkingPort() {} + + void IPv6OverGeoNetworkingPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void IPv6OverGeoNetworkingPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void IPv6OverGeoNetworkingPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void IPv6OverGeoNetworkingPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void IPv6OverGeoNetworkingPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void IPv6OverGeoNetworkingPort::Handle_Timeout(double time_since_last_call) {}*/ + + void IPv6OverGeoNetworkingPort::user_map(const char * /*system_port*/) {} + + void IPv6OverGeoNetworkingPort::user_unmap(const char * /*system_port*/) {} + + void IPv6OverGeoNetworkingPort::user_start() {} + + void IPv6OverGeoNetworkingPort::user_stop() {} + + void IPv6OverGeoNetworkingPort::outgoing_send(const LibItsIpv6OverGeoNetworking__TypesAndValues::IPv6OverGeoNetworkingReq & /*send_par*/) {} + +} // namespace LibItsIpv6OverGeoNetworking__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.hh b/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.hh index 05440fc877a63398b8af0463f0a9672224900084..f1099f77b1c7142d04c6336dff9fb94491099b07 100644 --- a/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.hh +++ b/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/IPv6OverGeoNetworkingPort.hh @@ -1,43 +1,43 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 09:18:30 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef IPv6OverGeoNetworkingPort_HH -#define IPv6OverGeoNetworkingPort_HH - -#include "LibItsIpv6OverGeoNetworking_TestSystem.hh" - -namespace LibItsIpv6OverGeoNetworking__TestSystem { - - class IPv6OverGeoNetworkingPort : public IPv6OverGeoNetworkingPort_BASE { - public: - IPv6OverGeoNetworkingPort(const char *par_port_name = NULL); - ~IPv6OverGeoNetworkingPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const IPv6OverGeoNetworkingReq &send_par); - }; - -} // namespace LibItsIpv6OverGeoNetworking__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 09:18:30 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef IPv6OverGeoNetworkingPort_HH +#define IPv6OverGeoNetworkingPort_HH + +#include "LibItsIpv6OverGeoNetworking_TestSystem.hh" + +namespace LibItsIpv6OverGeoNetworking__TestSystem { + + class IPv6OverGeoNetworkingPort : public IPv6OverGeoNetworkingPort_BASE { + public: + IPv6OverGeoNetworkingPort(const char *par_port_name = NULL); + ~IPv6OverGeoNetworkingPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsIpv6OverGeoNetworking__TypesAndValues::IPv6OverGeoNetworkingReq &send_par); + }; + +} // namespace LibItsIpv6OverGeoNetworking__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/module.mk b/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/module.mk index 507dcc447a478ac4637e99425415cf7525d146b6..ca9768e915abfe0f1fcc00197d94699622c42d0a 100644 --- a/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/IPv6oGN_ports/module.mk @@ -1,3 +1,3 @@ -sources := IPv6OverGeoNetworkingPort.cc -includes := . - +sources := IPv6OverGeoNetworkingPort.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.cc b/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.cc index 8aa5728a86456531a98424f4a96bd433c7892cd5..d379b20d7d9731bcca6878c9748c253830c02763 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.cc +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.cc @@ -1,68 +1,68 @@ -#include "loggers.hh" -#include "registration.hh" - -#include "ivim_layer.hh" - -//============================================================================= -#include "AdapterControlPort_IVIM.hh" -namespace LibItsIvim__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - ivim_layer *p = registration::get_instance().get_item(std::string("IVIM")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: IVIM not registered"); - } - } - -} // namespace LibItsIvim__TestSystem +#include "loggers.hh" +#include "registration.hh" + +#include "ivim_layer.hh" + +//============================================================================= +#include "AdapterControlPort_IVIM.hh" +namespace LibItsIvim__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive & /*send_par*/) {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + ivim_layer *p = registration::get_instance().get_item(std::string("IVIM")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: IVIM not registered"); + } + } + +} // namespace LibItsIvim__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.hh b/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.hh index 9be0e2cd934a3a675f080a025af506931a450f43..cc6a1566f1a646393f55f0bca92faa2500d0f3c5 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.hh +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/AdapterControlPort_IVIM.hh @@ -1,36 +1,36 @@ -//============================================================================= -#ifndef AdapterControlPort_IVIM_HH -#define AdapterControlPort_IVIM_HH - -#include "LibItsIvim_TestSystem.hh" - -namespace LibItsIvim__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsIvim__TestSystem -#endif +//============================================================================= +#ifndef AdapterControlPort_IVIM_HH +#define AdapterControlPort_IVIM_HH + +#include "LibItsIvim_TestSystem.hh" + +namespace LibItsIvim__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcGnssPrimitive &send_par); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsIvim__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.cc b/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.cc index 319ba7217e8d8cfabd54c838f1e496a3dca9ee19..8a2d75d525ff6d6f8f0035dbc5f50c1e118b6923 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.cc +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.cc @@ -66,7 +66,7 @@ namespace LibItsIvim__TestSystem { void IvimPort::user_stop() {} - void IvimPort::outgoing_send(const IvimReq &send_par) { + void IvimPort::outgoing_send(const LibItsIvim__TypesAndValues::IvimReq &send_par) { loggers::get_instance().log_msg(">>> IvimPort::outgoing_send: payload=", send_par); float duration; @@ -76,7 +76,7 @@ namespace LibItsIvim__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void IvimPort::outgoing_send(const IvimInd &send_par) { + void IvimPort::outgoing_send(const LibItsIvim__TypesAndValues::IvimInd &send_par) { loggers::get_instance().log_msg(">>> IvimPort::outgoing_send: payload=", send_par); float duration; @@ -86,7 +86,7 @@ namespace LibItsIvim__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void IvimPort::receiveMsg(const LibItsIvim__TestSystem::IvimInd &p_ind, const params &p_params) { + void IvimPort::receiveMsg(const LibItsIvim__TypesAndValues::IvimInd &p_ind, const params &p_params) { loggers::get_instance().log_msg(">>> IvimPort::receive_msg: ", p_ind); incoming_message(p_ind); diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.hh b/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.hh index db26886c67f934794c326bbb344e16e1d8ef17e2..fee64d4e7c507975fa08831cb5e0bb4a4677dff7 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.hh +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/IvimPort.hh @@ -26,7 +26,7 @@ namespace LibItsIvim__TestSystem { void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const LibItsIvim__TestSystem::IvimInd &, const params &); + void receiveMsg(const LibItsIvim__TypesAndValues::IvimInd &, const params &); private: /* void Handle_Fd_Event(int fd, boolean is_readable, @@ -42,8 +42,8 @@ namespace LibItsIvim__TestSystem { void user_start(); void user_stop(); - void outgoing_send(const IvimReq &send_par); - void outgoing_send(const IvimInd &send_par); + void outgoing_send(const LibItsIvim__TypesAndValues::IvimReq &send_par); + void outgoing_send(const LibItsIvim__TypesAndValues::IvimInd &send_par); }; } // namespace LibItsIvim__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.cc b/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.cc index 259ce1961de96a2d21c5ea6c6878b5800e995dbb..1d2a5f839cc7c1baffdc9da39e26c6168d07d31b 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.cc +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.cc @@ -1,115 +1,115 @@ -#include "uppertester_ivim_factory.hh" - -#include "UpperTesterPort_IVIM.hh" -#include "loggers.hh" -//============================================================================= -namespace LibItsIvim__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Ivim::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_Ivim::UpperTesterPort_Ivim"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_Ivim::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Ivim::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_Ivim::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_Ivim::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_Ivim::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Ivim::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_Ivim::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - loggers::get_instance().log("UpperTesterPort_Ivim::receive_msg: %s", p_ind.get_descriptor()->name); - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimResults") == 0) { // TODO To be refined - incoming_message((LibItsIvim__TypesAndValues::UtIvimResults &)p_ind); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } - } - -} // namespace LibItsIvim__TestSystem +#include "uppertester_ivim_factory.hh" + +#include "UpperTesterPort_IVIM.hh" +#include "loggers.hh" +//============================================================================= +namespace LibItsIvim__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Ivim::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_Ivim::UpperTesterPort_Ivim"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_Ivim::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Ivim::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_Ivim::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_Ivim::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_Ivim::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Ivim::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_Ivim::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + loggers::get_instance().log("UpperTesterPort_Ivim::receive_msg: %s", p_ind.get_descriptor()->name); + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimResults") == 0) { // TODO To be refined + incoming_message((LibItsIvim__TypesAndValues::UtIvimResults &)p_ind); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } + } + +} // namespace LibItsIvim__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.hh b/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.hh index 40b04709ff17b43d29f3c48a9f203c25015050b6..0e530ebc8dfbd3cd268f28b0d948ffe826ae6af1 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.hh +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/UpperTesterPort_IVIM.hh @@ -1,49 +1,49 @@ -//============================================================================= -#ifndef UpperTesterPort_IVIM_HH -#define UpperTesterPort_IVIM_HH - -#include "layer.hh" -#include "params.hh" - -#include "LibItsIvim_TestSystem.hh" -namespace LibItsIvim__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par); - - void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par); - - void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par); - - void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par); - }; - -} // namespace LibItsIvim__TestSystem +//============================================================================= +#ifndef UpperTesterPort_IVIM_HH +#define UpperTesterPort_IVIM_HH + +#include "layer.hh" +#include "params.hh" + +#include "LibItsIvim_TestSystem.hh" +namespace LibItsIvim__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par); + + void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par); + + void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par); + + void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par); + }; + +} // namespace LibItsIvim__TestSystem #endif \ No newline at end of file diff --git a/ccsrc/Ports/LibIts_ports/IVIM_ports/module.mk b/ccsrc/Ports/LibIts_ports/IVIM_ports/module.mk index de5f67150f176033c4c7e20c979c4b741d5b43f1..5eb25adb519096471f42650e0c5c5fed5ed6749b 100644 --- a/ccsrc/Ports/LibIts_ports/IVIM_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/IVIM_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_IVIM.cc IvimPort.cc UpperTesterPort_IVIM.cc -includes := . - +sources := AdapterControlPort_IVIM.cc IvimPort.cc UpperTesterPort_IVIM.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.cc b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.cc index a5304c25e57c3bd12387d681026149a3067d047b..82f3f30d4d8b80f687e9819f884cdb668170849e 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.cc +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.cc @@ -1,66 +1,66 @@ -#include "loggers.hh" -#include "registration.hh" - -#include "mapem_spatem_layer.hh" - -//============================================================================= -#include "AdapterControlPort_MapemSpatem.hh" -namespace LibItsMapemSpatem__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - mapem_spatem_layer *p = registration::get_instance().get_item(std::string("MapemSpatem")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: MapemSpatem not registered"); - } - } - -} // namespace LibItsMapemSpatem__TestSystem +#include "loggers.hh" +#include "registration.hh" + +#include "mapem_spatem_layer.hh" + +//============================================================================= +#include "AdapterControlPort_MapemSpatem.hh" +namespace LibItsMapemSpatem__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + mapem_spatem_layer *p = registration::get_instance().get_item(std::string("MapemSpatem")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: MapemSpatem not registered"); + } + } + +} // namespace LibItsMapemSpatem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.hh b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.hh index 6703bb84804470e1d06055d8c28f1d0f2de9fe8e..6692642f92d7fc10f587d132fa793ad3dc046c38 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.hh +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/AdapterControlPort_MapemSpatem.hh @@ -1,34 +1,34 @@ -//============================================================================= -#ifndef AdapterControlPort_MapemSpatem_HH -#define AdapterControlPort_MapemSpatem_HH - -#include "LibItsMapemSpatem_TestSystem.hh" - -namespace LibItsMapemSpatem__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsMapemSpatem__TestSystem -#endif +//============================================================================= +#ifndef AdapterControlPort_MapemSpatem_HH +#define AdapterControlPort_MapemSpatem_HH + +#include "LibItsMapemSpatem_TestSystem.hh" + +namespace LibItsMapemSpatem__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsMapemSpatem__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.cc b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.cc index 1a3ed7ac115f9d252220f08bc57988fcde6946d9..d8780415c0d5d48aeb750938288bd341ad4aca61 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.cc +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.cc @@ -66,7 +66,7 @@ namespace LibItsMapemSpatem__TestSystem { void MapemSpatemPort::user_stop() {} - void MapemSpatemPort::outgoing_send(const MapemReq &send_par) { + void MapemSpatemPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::MapemReq &send_par) { loggers::get_instance().log_msg(">>> MapemSpatemPort::outgoing_send: payload=", send_par); float duration; @@ -76,7 +76,7 @@ namespace LibItsMapemSpatem__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void MapemSpatemPort::outgoing_send(const SpatemReq &send_par) { + void MapemSpatemPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::SpatemReq &send_par) { loggers::get_instance().log_msg(">>> MapemSpatemPort::outgoing_send: payload=", send_par); float duration; @@ -86,13 +86,13 @@ namespace LibItsMapemSpatem__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void MapemSpatemPort::receiveMsg(const LibItsMapemSpatem__TestSystem::MapemInd &p_ind, const params &p_params) { + void MapemSpatemPort::receiveMsg(const LibItsMapemSpatem__TypesAndValues::MapemInd &p_ind, const params &p_params) { loggers::get_instance().log_msg(">>> MapemSpatemPort::receive_msg: ", p_ind); incoming_message(p_ind); } - void MapemSpatemPort::receiveMsg(const LibItsMapemSpatem__TestSystem::SpatemInd &p_ind, const params &p_params) { + void MapemSpatemPort::receiveMsg(const LibItsMapemSpatem__TypesAndValues::SpatemInd &p_ind, const params &p_params) { loggers::get_instance().log_msg(">>> MapemSpatemPort::receive_msg: ", p_ind); incoming_message(p_ind); diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.hh b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.hh index de70eaeedeadc359372aeacf85ed691f59ea247f..6195a5ae8dc11be3b843604db93f387aa9d9eaa9 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.hh +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/MapemSpatemPort.hh @@ -26,9 +26,9 @@ namespace LibItsMapemSpatem__TestSystem { void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const LibItsMapemSpatem__TestSystem::MapemInd &, const params &); + void receiveMsg(const LibItsMapemSpatem__TypesAndValues::MapemInd &, const params &); - void receiveMsg(const LibItsMapemSpatem__TestSystem::SpatemInd &, const params &); + void receiveMsg(const LibItsMapemSpatem__TypesAndValues::SpatemInd &, const params &); private: /* void Handle_Fd_Event(int fd, boolean is_readable, @@ -44,9 +44,9 @@ namespace LibItsMapemSpatem__TestSystem { void user_start(); void user_stop(); - void outgoing_send(const MapemReq &send_par); + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::MapemReq &send_par); - void outgoing_send(const SpatemReq &send_par); + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::SpatemReq &send_par); }; } // namespace LibItsMapemSpatem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.cc b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.cc index 1bc6e2c05bc833d12114aa7e85de1207f7876339..7e1108096dada665f4a4b7eb1439167f410798c3 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.cc +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.cc @@ -1,101 +1,101 @@ -#include "uppertester_mapem_spatem_factory.hh" - -#include "UpperTesterPort_MapemSpatem.hh" -#include "loggers.hh" -//============================================================================= -namespace LibItsMapemSpatem__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_MapemSpatem::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_MapemSpatem::UpperTesterPort_MapemSpatem"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_MapemSpatem::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_MapemSpatem::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_MapemSpatem::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_MapemSpatem::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_MapemSpatem::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_MapemSpatem::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_MapemSpatem::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - loggers::get_instance().log("UpperTesterPort_MapemSpatem::receive_msg: %s", p_ind.get_descriptor()->name); - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsMapemSpatem_TypesAndValues.UtMapemSpatemResults") == 0) { // TODO To be refined - incoming_message((LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &)p_ind); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsMapemSpatem_TypesAndValues.UtMapemEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsMapemSpatem_TypesAndValues.UtSpatemEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } else { - loggers::get_instance().warning("UpperTesterPort_MapemSpatem::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); - } - } - -} // namespace LibItsMapemSpatem__TestSystem +#include "uppertester_mapem_spatem_factory.hh" + +#include "UpperTesterPort_MapemSpatem.hh" +#include "loggers.hh" +//============================================================================= +namespace LibItsMapemSpatem__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_MapemSpatem::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_MapemSpatem::UpperTesterPort_MapemSpatem"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_MapemSpatem::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_MapemSpatem::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_MapemSpatem::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_MapemSpatem::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_MapemSpatem::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_MapemSpatem::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_MapemSpatem::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + loggers::get_instance().log("UpperTesterPort_MapemSpatem::receive_msg: %s", p_ind.get_descriptor()->name); + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsMapemSpatem_TypesAndValues.UtMapemSpatemResults") == 0) { // TODO To be refined + incoming_message((LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &)p_ind); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsMapemSpatem_TypesAndValues.UtMapemEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsMapemSpatem_TypesAndValues.UtSpatemEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } else { + loggers::get_instance().warning("UpperTesterPort_MapemSpatem::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); + } + } + +} // namespace LibItsMapemSpatem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.hh b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.hh index f3562501a405c11d6bca804d355471ed0cc0dfe3..4195d03713f38dd44d4b27bba47e113f807d3a08 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.hh +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/UpperTesterPort_MapemSpatem.hh @@ -1,46 +1,46 @@ -//============================================================================= -#ifndef UpperTesterPort_MapemSpatem_HH -#define UpperTesterPort_MapemSpatem_HH - -#include "LibItsMapemSpatem_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsMapemSpatem__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par); - - void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par); - }; - -} // namespace LibItsMapemSpatem__TestSystem -#endif +//============================================================================= +#ifndef UpperTesterPort_MapemSpatem_HH +#define UpperTesterPort_MapemSpatem_HH + +#include "LibItsMapemSpatem_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsMapemSpatem__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par); + + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par); + }; + +} // namespace LibItsMapemSpatem__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/module.mk b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/module.mk index 5a934dc21c9ff64253c257da291da1b9a21bfb4a..24fa5f4846b8bbd5cbaa05cf5ad91a870a259281 100644 --- a/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/MapemSpatem_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_MapemSpatem.cc MapemSpatemPort.cc UpperTesterPort_MapemSpatem.cc -includes := . - +sources := AdapterControlPort_MapemSpatem.cc MapemSpatemPort.cc UpperTesterPort_MapemSpatem.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.cc b/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.cc index 674c167f774ae53617555d46f625da8d2e9a0ce9..77514a32b116ee7f2d06ba46f28b0c859a7005a9 100644 --- a/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.cc +++ b/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.cc @@ -1,61 +1,61 @@ -#include - -#include "loggers.hh" -#include "registration.hh" - -#include "AdapterControlPort_Pki.hh" -//============================================================================= -namespace LibItsPki__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name), _params() { - loggers::get_instance().log("AdapterControlPort::AdapterControlPort"); - } - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("AdapterControlPort::set_parameter: %s=%s", parameter_name, parameter_value); - } - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_map: %s", system_port); } - - void AdapterControlPort::user_unmap(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_unmap: %s", system_port); } - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsPki__TypesAndValues::AcPkiPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - pki_layer *p = registration::get_instance().get_item(std::string("PKI")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got PKI layer %p", p); - LibItsPki__TypesAndValues::AcPkiResponse response; - response.result() = BOOLEAN(false); - if (send_par.ischosen(LibItsPki__TypesAndValues::AcPkiPrimitive::ALT_acSetSecurityData)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: AcSetSecurityData"); - p->set_pki_keys(send_par.acSetSecurityData()); - response.result() = BOOLEAN(true); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: pkiPort not registered"); - } - } - -} // namespace LibItsPki__TestSystem +#include + +#include "loggers.hh" +#include "registration.hh" + +#include "AdapterControlPort_Pki.hh" +//============================================================================= +namespace LibItsPki__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name), _params() { + loggers::get_instance().log("AdapterControlPort::AdapterControlPort"); + } + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("AdapterControlPort::set_parameter: %s=%s", parameter_name, parameter_value); + } + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_map: %s", system_port); } + + void AdapterControlPort::user_unmap(const char *system_port) { loggers::get_instance().log(">>> AdapterControlPort::user_unmap: %s", system_port); } + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsPki__TypesAndValues::AcPkiPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + pki_layer *p = registration::get_instance().get_item(std::string("PKI")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got PKI layer %p", p); + LibItsPki__TypesAndValues::AcPkiResponse response; + response.result() = BOOLEAN(false); + if (send_par.ischosen(LibItsPki__TypesAndValues::AcPkiPrimitive::ALT_acSetSecurityData)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: AcSetSecurityData"); + p->set_pki_keys(send_par.acSetSecurityData()); + response.result() = BOOLEAN(true); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: pkiPort not registered"); + } + } + +} // namespace LibItsPki__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.hh b/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.hh index 1c5476bebab6e0dc08327298c60c65238806b5cc..a87814a991e16ff4f3a5c7dea1fdef801cea35bc 100644 --- a/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.hh +++ b/ccsrc/Ports/LibIts_ports/Pki_ports/AdapterControlPort_Pki.hh @@ -1,38 +1,38 @@ -//============================================================================= -#ifndef AdapterControlPort_Pki_HH -#define AdapterControlPort_Pki_HH - -#include "LibItsPki_TestSystem.hh" - -#include "params.hh" - -namespace LibItsPki__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - params _params; - - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsPki__TypesAndValues::AcPkiPrimitive &send_par); - }; - -} // namespace LibItsPki__TestSystem +//============================================================================= +#ifndef AdapterControlPort_Pki_HH +#define AdapterControlPort_Pki_HH + +#include "LibItsPki_TestSystem.hh" + +#include "params.hh" + +namespace LibItsPki__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + params _params; + + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsPki__TypesAndValues::AcPkiPrimitive &send_par); + }; + +} // namespace LibItsPki__TestSystem #endif \ No newline at end of file diff --git a/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.cc b/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.cc index 4f840fb80ccc3362239a28fc88b1c7815dff984c..f0a4d9930039adebbd2b000315dd98aebeea41a0 100644 --- a/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.cc +++ b/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.cc @@ -1,101 +1,101 @@ -#include - -#include "UpperTesterPkiPort.hh" - -#include "loggers.hh" - -#include "uppertester_pki_layer.hh" -#include "uppertester_pki_layer_factory.hh" - -//============================================================================= -namespace LibItsPki__TestSystem { - - UpperTesterPkiPort::UpperTesterPkiPort(const char *par_port_name) - : UpperTesterPkiPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPkiPort_Pki::outgoing_send") { - loggers::get_instance().log("UpperTesterPkiPort_Pki::UpperTesterPkiPort_Pki"); - } - - UpperTesterPkiPort::~UpperTesterPkiPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPkiPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPkiPort_Pki::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPkiPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPkiPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPkiPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPkiPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPkiPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPkiPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPkiPort_Pki::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPkiPort_Pki::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPkiPort_Pki::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPkiPort_Pki::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPkiPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPkiPort_Pki::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPkiPort::user_start() {} - - void UpperTesterPkiPort::user_stop() {} - - void UpperTesterPkiPort::outgoing_send(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPkiPort::outgoing_send(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPkiPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPkiPort_Pki::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsPki_TypesAndValues.UtPkiResults") == 0) { // TODO To be refined - incoming_message(static_cast(p_ind)); - } else { - loggers::get_instance().warning("UpperTesterPkiPort_Pki::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); - } - } - -} // namespace LibItsPki__TestSystem +#include + +#include "UpperTesterPkiPort.hh" + +#include "loggers.hh" + +#include "uppertester_pki_layer.hh" +#include "uppertester_pki_layer_factory.hh" + +//============================================================================= +namespace LibItsPki__TestSystem { + + UpperTesterPkiPort::UpperTesterPkiPort(const char *par_port_name) + : UpperTesterPkiPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPkiPort_Pki::outgoing_send") { + loggers::get_instance().log("UpperTesterPkiPort_Pki::UpperTesterPkiPort_Pki"); + } + + UpperTesterPkiPort::~UpperTesterPkiPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPkiPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPkiPort_Pki::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPkiPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPkiPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPkiPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPkiPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPkiPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPkiPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPkiPort_Pki::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPkiPort_Pki::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPkiPort_Pki::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPkiPort_Pki::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPkiPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPkiPort_Pki::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPkiPort::user_start() {} + + void UpperTesterPkiPort::user_stop() {} + + void UpperTesterPkiPort::outgoing_send(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPkiPort::outgoing_send(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPkiPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPkiPort_Pki::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsPki_TypesAndValues.UtPkiResults") == 0) { // TODO To be refined + incoming_message(static_cast(p_ind)); + } else { + loggers::get_instance().warning("UpperTesterPkiPort_Pki::receive_msg: Message not processed: %s", p_ind.get_descriptor()->name); + } + } + +} // namespace LibItsPki__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.hh b/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.hh index 20d547b2819040e56c715f097929f81c1768758a..3be86c267bd8b5081aa87e3d6a09af9ab9e3f111 100644 --- a/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.hh +++ b/ccsrc/Ports/LibIts_ports/Pki_ports/UpperTesterPkiPort.hh @@ -1,46 +1,46 @@ -#ifndef UpperTesterPkiPort_HH -#define UpperTesterPkiPort_HH - -//============================================================================= -#include "LibItsPki_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsPki__TestSystem { - - class UpperTesterPkiPort : public UpperTesterPkiPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPkiPort(const char *par_port_name = NULL); - ~UpperTesterPkiPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par); - - void outgoing_send(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par); - }; - -} // namespace LibItsPki__TestSystem -#endif +#ifndef UpperTesterPkiPort_HH +#define UpperTesterPkiPort_HH + +//============================================================================= +#include "LibItsPki_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsPki__TestSystem { + + class UpperTesterPkiPort : public UpperTesterPkiPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPkiPort(const char *par_port_name = NULL); + ~UpperTesterPkiPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par); + + void outgoing_send(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par); + }; + +} // namespace LibItsPki__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/Pki_ports/module.mk b/ccsrc/Ports/LibIts_ports/Pki_ports/module.mk index 1897e76b0402c01137b6cc869a0cb9c484ea2694..81692168677b88c6e62b43c1eb3490a94af7ad7f 100644 --- a/ccsrc/Ports/LibIts_ports/Pki_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/Pki_ports/module.mk @@ -1,3 +1,3 @@ -sources := UpperTesterPkiPort.cc -includes := . - +sources := UpperTesterPkiPort.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.cc b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.cc index 958e340743ed2ff7807da2fab58be8b64f80fff5..682a5e70933fd7987977db48ec32cef547507084 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.cc +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.cc @@ -1,57 +1,57 @@ -#include -//#include - -#include "ConfigRsuSimulatorCodec.hh" -#include "loggers.hh" - -#include "ItsRSUsSimulator_TestSystem.hh" - -int ConfigRsuSimulatorCodec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorCodec::encode: ", (const Base_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - - loggers::get_instance().log_msg("<<< ConfigRsuSimulatorCodec::encode: data=", data); - return 0; -} - -int ConfigRsuSimulatorCodec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> ConfigRsuSimulatorCodec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorCodec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("ConfigRsuSimulatorCodec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("ConfigRsuSimulatorCodec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("ConfigRsuSimulatorCodec::encode_: -1 result code returned"); - return -1; - } - } - } // End of 'for' statement - } else { - loggers::get_instance().log("ConfigRsuSimulatorCodec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - - loggers::get_instance().log_to_hexa("<<>> ConfigRsuSimulatorCodec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< ConfigRsuSimulatorCodec::decode: ", (const Base_Type &)msg); - return 0; -} +#include +//#include + +#include "ConfigRsuSimulatorCodec.hh" +#include "loggers.hh" + +#include "ItsRSUsSimulator_TestSystem.hh" + +int ConfigRsuSimulatorCodec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorCodec::encode: ", (const Base_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + + loggers::get_instance().log_msg("<<< ConfigRsuSimulatorCodec::encode: data=", data); + return 0; +} + +int ConfigRsuSimulatorCodec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> ConfigRsuSimulatorCodec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorCodec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("ConfigRsuSimulatorCodec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("ConfigRsuSimulatorCodec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("ConfigRsuSimulatorCodec::encode_: -1 result code returned"); + return -1; + } + } + } // End of 'for' statement + } else { + loggers::get_instance().log("ConfigRsuSimulatorCodec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + + loggers::get_instance().log_to_hexa("<<>> ConfigRsuSimulatorCodec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< ConfigRsuSimulatorCodec::decode: ", (const Base_Type &)msg); + return 0; +} diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.hh b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.hh index d8ce985a07774a5f26cf8a3b49d4ec77d442de39..7b31e4702c97c8d9ffd88cbb08281e613b3733f3 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.hh +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorCodec.hh @@ -1,24 +1,24 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -class Record_Type; -class Base_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace ItsRSUsSimulator__TestSystem { - class CfInitialize; -} - -class ConfigRsuSimulatorCodec : public codec { - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - explicit ConfigRsuSimulatorCodec() : codec(){}; - virtual ~ConfigRsuSimulatorCodec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); -}; // End of class ConfigRsuSimulatorCodec +#pragma once + +#include "codec.hh" +#include "params.hh" + +class Record_Type; +class Base_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace ItsRSUsSimulator__TestSystem { + class CfInitialize; +} + +class ConfigRsuSimulatorCodec : public codec { + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + explicit ConfigRsuSimulatorCodec() : codec(){}; + virtual ~ConfigRsuSimulatorCodec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); +}; // End of class ConfigRsuSimulatorCodec diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.cc b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.cc index d49addc03b15f2376d2e56ddbdf981d385c2901a..7e436bc23f164ce005ef9c08918ee53085a80f98 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.cc +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.cc @@ -1,1380 +1,1380 @@ -#include "ConfigRsuSimulatorLayerFactory.hh" - -#include "loggers.hh" - -#include "ItsRSUsSimulator_TestSystem.hh" - -#include "LibCommon_BasicTypesAndValues.hh" - -#include "UpperTesterRtcmemCodec.hh" -#include "UpperTesterSremSsemCodec.hh" -#include "uppertester_cam_codec.hh" -#include "uppertester_denm_codec.hh" -#include "uppertester_geonetworking_codec.hh" -#include "uppertester_ivim_codec.hh" -#include "uppertester_mapem_spatem_codec.hh" - -#include "LibItsCam_EncdecDeclarations.hh" -#include "LibItsDenm_EncdecDeclarations.hh" -#include "LibItsIvim_EncdecDeclarations.hh" -#include "LibItsMapemSpatem_EncdecDeclarations.hh" -#include "LibItsRtcmem_EncdecDeclarations.hh" -#include "LibItsSremSsem_EncdecDeclarations.hh" - -ConfigRsuSimulatorLayer::ConfigRsuSimulatorLayer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec(), _codec_cam() { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::ConfigRsuSimulatorLayer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); -} - -void ConfigRsuSimulatorLayer::sendMsg(const ItsRSUsSimulator__TestSystem::CfInitialize &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - // Encode ConfigRsuSimulator PDU - OCTETSTRING data; - if (_codec.encode(static_cast(send_par), data) == -1) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Encoding failure"); - return; - } - - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnResults::ALT_utGnInitializeResult)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utGnInitializeResult())); - } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnResults::ALT_utGnTriggerResult)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTriggerResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utGnTriggerResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtGnResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnEventIndication)); - OCTETSTRING l = int2oct(send_par.rawPayload().lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(send_par.rawPayload().lengthof(), static_cast(send_par.rawPayload())); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsCam__TypesAndValues::UtCamResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsCam__TypesAndValues::UtCamResults::ALT_utCamInitializeResult)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utCamInitializeResult())); - } else if (send_par.ischosen(LibItsCam__TypesAndValues::UtCamResults::ALT_utCamTriggerResult)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamTriggerResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utCamTriggerResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtCamResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsCam__TypesAndValues::UtCamEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamEventInd)); - BITSTRING bs = LibItsCam__EncdecDeclarations::fx__enc__CAM(send_par.camMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmInitializeResult)) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utDenmInitializeResult())); - } else if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmTriggerResult)) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmTriggerResult)); - const LibItsDenm__TypesAndValues::UtDenmTriggerResult &r = send_par.utDenmTriggerResult(); - encoding_buffer.put_c((unsigned char)static_cast(r.result())); - OCTETSTRING os = int2oct(r.actionId().originatingStationID(), 4); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - os = int2oct(r.actionId().sequenceNumber(), 2); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - } else if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmUpdateResult)) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmUpdateResult)); - const LibItsDenm__TypesAndValues::UtDenmUpdateResult &r = send_par.utDenmUpdateResult(); - encoding_buffer.put_c((unsigned char)static_cast(r.result())); - OCTETSTRING os = int2oct(r.actionId().originatingStationID(), 4); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - os = int2oct(r.actionId().sequenceNumber(), 2); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - } else if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmTerminationResult)) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utDenmTerminationResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtDenmResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmEventIndication)); - BITSTRING bs = LibItsDenm__EncdecDeclarations::fx__enc__DENM(send_par.denMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsPki__TypesAndValues::UtPkiResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsPki__TypesAndValues::UtPkiResults::ALT_utPkiInitializeResult)) { - encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utPkiInitializeResult())); - } else if (send_par.ischosen(LibItsPki__TypesAndValues::UtPkiResults::ALT_utPkiTriggerResult)) { - encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiTriggerResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utPkiTriggerResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtPkiResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimInitializeResult)) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utIvimInitializeResult())); - } else if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimTriggerResult)) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTriggerResult)); - const LibItsIvim__TypesAndValues::UtIvimTriggerResult &r = - dynamic_cast(send_par.utIvimTriggerResult()); - encoding_buffer.put_c((unsigned char)static_cast(r.result())); - OCTETSTRING os = int2oct(r.iviIdentificationNumber(), 2); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - } else if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimUpdateResult)) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimUpdateResult)); - const LibItsIvim__TypesAndValues::UtIvimUpdateResult &r = - dynamic_cast(send_par.utIvimUpdateResult()); - encoding_buffer.put_c((unsigned char)static_cast(r.result())); - OCTETSTRING os = int2oct(r.iviIdentificationNumber(), 2); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - } else if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimTerminationResult)) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTerminationResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utIvimTerminationResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtIvimResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimEventIndication)); - BITSTRING bs = LibItsIvim__EncdecDeclarations::fx__enc__IVIM(send_par.iviMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults::ALT_utMapemSpatemInitializeResult)) { - encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utMapemSpatemInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utMapemSpatemInitializeResult())); - } else if (send_par.ischosen(LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults::ALT_utMapemSpatemTriggerResult)) { - encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utMapemSpatemTriggerResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utMapemSpatemTriggerResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtMapemSpatemResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utMapemEventIndication)); - BITSTRING bs = LibItsMapemSpatem__EncdecDeclarations::fx__enc__MAPEM(send_par.mapeMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utSpatemEventIndication)); - BITSTRING bs = LibItsMapemSpatem__EncdecDeclarations::fx__enc__SPATEM(send_par.spateMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremInitializeResult)) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremInitializeResult())); - } else if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremTriggerResult)) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremTriggerResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremTriggerResult())); - } else if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremUpdateResult)) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremUpdateResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremUpdateResult())); - } else if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremCancelationResult)) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremCancelationResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremCancelationResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtSremResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremEventIndication)); - BITSTRING bs = LibItsSremSsem__EncdecDeclarations::fx__enc__SREM(send_par.sreMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSsemEventIndication)); - BITSTRING bs = LibItsSremSsem__EncdecDeclarations::fx__enc__SSEM(send_par.sseMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemInitializeResult)) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemInitializeResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemInitializeResult())); - } else if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemTriggerResult)) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTriggerResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemTriggerResult())); - } else if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemUpdateResult)) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemUpdateResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemUpdateResult())); - } else if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemTerminationResult)) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTerminationResult)); - encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemTerminationResult())); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtRtcmemResults variant"); - return; - } - - OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(os, _params); -} - -void ConfigRsuSimulatorLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); - - TTCN_Buffer encoding_buffer; - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemEventIndication)); - BITSTRING bs = LibItsRtcmem__EncdecDeclarations::fx__enc__RTCMEM(send_par.rtcmemMsg()); - OCTETSTRING os = bit2oct(bs); - OCTETSTRING l = int2oct(os.lengthof(), 2); - encoding_buffer.put_s(l.lengthof(), static_cast(l)); - encoding_buffer.put_s(os.lengthof(), static_cast(os)); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - send_data(data, _params); -} - -void ConfigRsuSimulatorLayer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::send_data: ", data); - - send_to_all_layers(data, params); -} - -void ConfigRsuSimulatorLayer::receive_data(OCTETSTRING &data, params ¶ms) { // FIXME To be moved into ConfigRsuSimulatorCodec - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::receive_data: ", data); - - unsigned char id = *(static_cast(data)); - if (id == 0x00) { // Receive an UtxxInitialise - process_utinitialize_data(data, params); - } else if (id == uppertester_cam_codec::c_utCamChangeCurvature) { - process_ut_cam_changecurvature_data(data, params); - } else if (id == uppertester_cam_codec::c_utCamChangeSpeed) { - process_ut_cam_changespeed_data(data, params); - } else if (id == uppertester_cam_codec::c_utCamChangeHeading) { - process_ut_cam_changeheading_data(data, params); - } else if (id == uppertester_cam_codec::c_utCamSetVehicleRole) { - process_ut_cam_setvehiclerole_data(data, params); - } else if (id == uppertester_denm_codec::c_utDenmTrigger) { - process_ut_denm_trigger(data, params); - } else if (id == uppertester_denm_codec::c_utDenmUpdate) { - process_ut_denm_update(data, params); - } else if (id == uppertester_denm_codec::c_utDenmTermination) { - process_ut_denm_termination(data, params); - } else if (id == uppertester_mapem_spatem_codec::c_utMapemSpatemTrigger) { - process_ut_mapem_spatem_trigger(data, params); - } else if (id == uppertester_ivim_codec::c_utIvimTrigger) { - process_ut_ivim_trigger(data, params); - } else if (id == uppertester_ivim_codec::c_utIvimUpdate) { - process_ut_ivim_update(data, params); - } else if (id == uppertester_ivim_codec::c_utIvimTermination) { - process_ut_ivim_termination(data, params); - } else if (id == UpperTesterSremSsemCodec::c_utSremTrigger) { - process_ut_srem_trigger(data, params); - } else if (id == UpperTesterSremSsemCodec::c_utSremUpdate) { - process_ut_srem_update(data, params); - } else if (id == UpperTesterSremSsemCodec::c_utSremCancelation) { - process_ut_srem_termination(data, params); - } else if (id == UpperTesterRtcmemCodec::c_utRtcmemTrigger) { - process_ut_rtcmem_trigger(data, params); - } else if (id == UpperTesterRtcmemCodec::c_utRtcmemUpdate) { - process_ut_rtcmem_update(data, params); - } else if (id == UpperTesterRtcmemCodec::c_utRtcmemTermination) { - process_ut_rtcmem_termination(data, params); - } else if ((id >= uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast) && - (id <= uppertester_geonetworking_codec::c_utGnTrigger_Tsb)) { // Receive an UtGnTrigger - process_ut_geonetworking_trigger(data, params); - } else if ((id == uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest) || - (id == uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest)) { // Receive an UtPkiTrigger - process_ut_pki_trigger(data, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::receive_data: Unsupported tag %02x", id); - } -} - -int ConfigRsuSimulatorLayer::process_utinitialize_data(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_utinitialize_data"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_utinitialize_data: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("gn") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsGeoNetworking__TypesAndValues::UtGnInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("cam") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsCam__TypesAndValues::UtCamInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("denm") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsDenm__TypesAndValues::UtDenmInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("pki") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsPki__TypesAndValues::UtPkiInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("ivim") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsIvim__TypesAndValues::UtIvimInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("mapemspatem") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("sremssem") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsSremSsem__TypesAndValues::UtSremInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else if (_params[std::string("ut")].compare("rtcmem") == 0) { - OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); - LibItsRtcmem__TypesAndValues::UtRtcmemInitialize p(hashedId); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_utinitialize_data: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("cam") == 0) { - OCTETSTRING speed(data.lengthof() - 1, 1 + static_cast(data)); - LibItsCam__TypesAndValues::UtCamTrigger p; - p.changeSpeed() = oct2int(speed); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("cam") == 0) { - OCTETSTRING curvature(data.lengthof() - 1, 1 + static_cast(data)); - LibItsCam__TypesAndValues::UtCamTrigger p; - p.changeCurvature() = oct2int(curvature); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("cam") == 0) { - OCTETSTRING heading(data.lengthof() - 1, 1 + static_cast(data)); - LibItsCam__TypesAndValues::UtCamTrigger p; - p.changeHeading() = oct2int(heading); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("cam") == 0) { - OCTETSTRING vehicle_role(data.lengthof() - 1, 1 + static_cast(data)); - LibItsCam__TypesAndValues::UtCamTrigger p; - p.setVehicleRole() = oct2int(vehicle_role); - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_denm_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_denm_trigger", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("denm") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_trigger: msg_id=%02x", msg_id); - unsigned char flag = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_trigger: flag=%02x", flag); - LibItsDenm__TypesAndValues::UtDenmTrigger trigger; // See ETSI TR 103 099 Cause C.4.1 GenerateDenmEvent - // Decode detectionTime - trigger.detectionTime() = oct2int(OCTETSTRING(6, p)); - p += 6; - // ValidityDuration - if ((flag & 0x80) == 0x80) { - trigger.validityDuration() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - trigger.validityDuration().set_to_omit(); - } - p += 3; - if ((flag & 0x40) == 0x40) { - trigger.repetitionDuration() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - trigger.repetitionDuration().set_to_omit(); - } - p += 3; - // Situation - trigger.situation().informationQuality() = oct2int(OCTETSTRING(1, p++)); - trigger.situation().eventType().causeCode() = oct2int(OCTETSTRING(1, p++)); - trigger.situation().eventType().subCauseCode() = oct2int(OCTETSTRING(1, p++)); - trigger.situation().linkedCause().set_to_omit(); - trigger.situation().eventHistory().set_to_omit(); - // RelevanceDistance - trigger.relevanceDistance() = oct2int(OCTETSTRING(1, p++)); - // RelevanceTrafficDirection - trigger.relevanceTrafficDirection() = oct2int(OCTETSTRING(1, p++)); - if ((flag & 0x04) == 0x04) { - trigger.transmissionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); - } else { - trigger.transmissionInterval().set_to_omit(); - } - p += 2; - if ((flag & 0x02) == 0x02) { - trigger.repetitionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); - } else { - trigger.repetitionInterval().set_to_omit(); - } - p += 2; - // alacarteLength - INTEGER alacarte_length = oct2int(OCTETSTRING(1, p)); - if (static_cast(alacarte_length) != 0) { - p += 1; - // FIXME AlacarteContainer alacarte optional - } else { - trigger.alacarte().set_to_omit(); - } - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_denm_trigger: ", trigger); - - // Pass it to the ports if any - to_all_upper_ports(trigger, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_denm_update(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_denm_update", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_update: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("denm") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_update: msg_id=%02x", msg_id); - unsigned char flag = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_update: flag=%02x", flag); - LibItsDenm__TypesAndValues::UtDenmUpdate update; // See ETSI TR 103 099 Cause C.4.1 GenerateDenmEvent - // Statuion ID - update.actionId().originatingStationID() = oct2int(OCTETSTRING(4, p)); - p += 4; - // SequenceNumber - update.actionId().sequenceNumber() = oct2int(OCTETSTRING(2, p)); - p += 2; - // Decode detectionTime - update.detectionTime() = oct2int(OCTETSTRING(6, p)); - p += 6; - if ((flag & 0x80) == 0x80) { - update.validityDuration() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - update.validityDuration().set_to_omit(); - } - p += 3; - // Situation - if ((flag & 0x40) == 0x40) { - DENM__PDU__Descriptions::SituationContainer &s = static_cast(*update.get_opt_value()); - s.informationQuality() = oct2int(OCTETSTRING(1, p++)); - s.eventType().causeCode() = oct2int(OCTETSTRING(1, p++)); - s.eventType().subCauseCode() = oct2int(OCTETSTRING(1, p++)); - s.linkedCause().set_to_omit(); - s.eventHistory().set_to_omit(); - update.situation() = OPTIONAL(s); - } else { - update.situation().set_to_omit(); - } - // Location - update.location().set_to_omit(); - // RelevanceDistance - if ((flag & 0x20) == 0x20) { - update.relevanceDistance() = oct2int(OCTETSTRING(1, p++)); - } else { - update.relevanceDistance().set_to_omit(); - } - // RelevanceTrafficDirection - if ((flag & 0x10) == 0x10) { - update.relevanceTrafficDirection() = oct2int(OCTETSTRING(1, p++)); - } else { - update.relevanceTrafficDirection().set_to_omit(); - } - if ((flag & 0x08) == 0x08) { - update.transmissionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); - } else { - update.transmissionInterval().set_to_omit(); - } - p += 2; - if ((flag & 0x04) == 0x04) { - update.repetitionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); - } else { - update.repetitionInterval().set_to_omit(); - } - p += 2; - // alacarteLength - INTEGER alacarte_length = oct2int(OCTETSTRING(1, p)); - if (static_cast(alacarte_length) != 0) { - p += 1; - // FIXME AlacarteContainer alacarte optional - } else { - update.alacarte().set_to_omit(); - } - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_denm_update: ", update); - - // Pass it to the ports if any - to_all_upper_ports(update, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_update: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_denm_termination(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_denm_termination"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_termination: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("denm") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_termination: msg_id=%02x", msg_id); - LibItsDenm__TypesAndValues::UtDenmTermination termination; - termination.actionId().originatingStationID() = oct2int(OCTETSTRING(4, p)); - p += 4; - termination.actionId().sequenceNumber() = oct2int(OCTETSTRING(2, p)); - - // Pass it to the ports if any - to_all_upper_ports(termination, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_termination: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("gn") == 0) { - unsigned char msg_id = *static_cast(data); - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id); - OCTETSTRING payload(data.lengthof() - 1, 1 + static_cast(data)); - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: payload:", payload); - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(payload); - - LibItsGeoNetworking__TypesAndValues::UtGnTrigger p; - if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast) { - LibItsGeoNetworking__TypesAndValues::GenerateGeoUnicastMessage g; - g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - if (g.payload().lengthof() > 2) { - g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); - } else { - g.payload() = OCTETSTRING(0, nullptr); - } - p.geoUnicast() = g; - } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast) { - LibItsGeoNetworking__TypesAndValues::GenerateGeoBroadcastMessage g; - g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - if (g.payload().lengthof() > 2) { - g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); - } else { - g.payload() = OCTETSTRING(0, nullptr); - } - p.geoBroadcast() = g; - } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_GeoAnycast) { - LibItsGeoNetworking__TypesAndValues::GenerateGeoAnycastMessage g; - g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - if (g.payload().lengthof() > 2) { - g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); - } else { - g.payload() = OCTETSTRING(0, nullptr); - } - p.geoAnycast() = g; - } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_Shb) { - LibItsGeoNetworking__TypesAndValues::GenerateSHBMessage g; - g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - if (g.payload().lengthof() > 2) { - g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); - } else { - g.payload() = OCTETSTRING(0, nullptr); - } - p.shb() = g; - } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_Tsb) { - LibItsGeoNetworking__TypesAndValues::GenerateTSBMessage g; - g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - if (g.payload().lengthof() > 2) { - g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); - } else { - g.payload() = OCTETSTRING(0, nullptr); - } - p.tsb() = g; - } - - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_pki_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_pki_trigger"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_pki_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("pki") == 0) { - unsigned char msg_id = *static_cast(data); - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id); - OCTETSTRING payload(data.lengthof() - 1, 1 + static_cast(data)); - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: payload:", payload); - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(payload); - - LibItsPki__TypesAndValues::UtPkiTrigger p; - if (msg_id == uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest) { - // LibItsPki__TypesAndValues::TriggerEnrolmentRequest e; - // e.decode(*e.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - // p.triggerEnrolmentRequest() = e; - p.triggerEnrolmentRequest().cannonicalId() = OCTETSTRING(0, nullptr); // No parameter used - p.triggerEnrolmentRequest().encAlgorithm() = OCTETSTRING(0, nullptr); // No parameter used - p.triggerEnrolmentRequest().privateKey() = OCTETSTRING(0, nullptr); // No parameter used - p.triggerEnrolmentRequest().compressedPublickey() = OCTETSTRING(0, nullptr); // No parameter used - } else if (msg_id == uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest) { - // LibItsPki__TypesAndValues::TriggerAuthorizationRequest e; - // e.decode(*e.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); - // p.triggerAuthorizationRequest() = e; - p.triggerAuthorizationRequest().cannonicalId() = OCTETSTRING(0, nullptr); // No parameter used - p.triggerAuthorizationRequest().encAlgorithm() = OCTETSTRING(0, nullptr); // No parameter used - p.triggerAuthorizationRequest().privateKey() = OCTETSTRING(0, nullptr); // No parameter used - p.triggerAuthorizationRequest().compressedPublickey() = OCTETSTRING(0, nullptr); // No parameter used - } - - // Pass it to the ports if any - to_all_upper_ports(p, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_pki_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("mapemspatem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: msg_id=%02x", msg_id); - unsigned char flag = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: flag=%02x", flag); - LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger trigger; // See ETSI TR 103 099 Cause C.4.1 GenerateMapemSpatemEvent - // Decode Event - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: event=%02x", *p); - trigger.event().int2enum(static_cast(*p++)); - // Decode IntersectionId - if ((flag & 0x80) == 0x80) { - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: intersectionID=%04x", (short)*p); - trigger.intersectionID() = OPTIONAL(static_cast((*p << 8) | *(p + 1))); - } else { - trigger.intersectionID().set_to_omit(); - } - p += 2; - // Decode RegulatorySpeedLimit - if ((flag & 0x40) == 0x40) { - DSRC__REGION__noCircular::RegulatorySpeedLimit r; - r.type__().int2enum(static_cast(*p++)); - r.speed() = static_cast((*p << 8) | *(p + 1)); - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: RegulatorySpeedLimit: ", r); - trigger.regulatorySpeedLimit() = OPTIONAL(r); - } else { - trigger.regulatorySpeedLimit().set_to_omit(); - } - p += 2; - // FIXME Add flags - // trigger.latitude().set_to_omit(); - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: ", trigger); - - // Pass it to the ports if any - to_all_upper_ports(trigger, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_ivim_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_ivim_trigger", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("ivim") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: msg_id=%02x", msg_id); - unsigned short flag = static_cast((*p++) << 8 | (*p++)); - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: flag=%02x", flag); - LibItsIvim__TypesAndValues::UtIvimTrigger trigger; // See ETSI TR 103 099 Cause C.4.1 GenerateIvimEvent - // Decode ValidityFrom - if ((flag & 0x8000) == 0x8000) { - trigger.validFrom() = OPTIONAL(oct2int(OCTETSTRING(6, p))); - } else { - trigger.validFrom().set_to_omit(); - } - p += 6; - // Decode ValidityTo - if ((flag & 0x4000) == 0x4000) { - trigger.validTo() = OPTIONAL(oct2int(OCTETSTRING(6, p))); - } else { - trigger.validTo().set_to_omit(); - } - p += 6; - // Decode RepetitionInterval - if ((flag & 0x2000) == 0x2000) { - trigger.repetitionInterval() = OPTIONAL(oct2int(OCTETSTRING(6, p))); - } else { - trigger.repetitionInterval().set_to_omit(); - } - p += 6; - // Decode zoneIds - if ((flag & 0x1000) == 0x1000) { - PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; - rov.set_size(*p++); - for (int i = 0; i < rov.size_of(); i++) { - rov[i] = oct2int(OCTETSTRING(1, p++)); - } - trigger.zoneIds() = OPTIONAL(rov); - } else { - trigger.zoneIds().set_to_omit(); - p += 1; - } - // Decode laneNumber - if ((flag & 0x0800) == 0x0800) { - trigger.laneNumber() = OPTIONAL(oct2int(OCTETSTRING(1, p))); - } else { - trigger.laneNumber().set_to_omit(); - } - p += 1; - // Decode relavanceZoneIds - if ((flag & 0x0400) == 0x0400) { - PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; - rov.set_size(*p++); - for (int i = 0; i < rov.size_of(); i++) { - rov[i] = oct2int(OCTETSTRING(1, p++)); - } - trigger.relavanceZoneIds() = OPTIONAL(rov); - } else { - trigger.relavanceZoneIds().set_to_omit(); - p += 1; - } - // Decode detectionZoneIds - if ((flag & 0x0200) == 0x0200) { - PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; - rov.set_size(*p++); - for (int i = 0; i < rov.size_of(); i++) { - rov[i] = oct2int(OCTETSTRING(1, p++)); - } - trigger.detectionZoneIds() = OPTIONAL(rov); - } else { - trigger.detectionZoneIds().set_to_omit(); - p += 1; - } - // Decode driverAwarenesZoneIds - if ((flag & 0x0100) == 0x0100) { - PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; - rov.set_size(*p++); - for (int i = 0; i < rov.size_of(); i++) { - rov[i] = oct2int(OCTETSTRING(1, p++)); - } - trigger.driverAwarenesZoneIds() = OPTIONAL(rov); - } else { - trigger.driverAwarenesZoneIds().set_to_omit(); - p += 1; - } - if ((flag & 0x0080) == 0x0080) { - CITSapplMgmtIDs::VarLengthNumber v; - v.content() = oct2int(OCTETSTRING(1, p)); - trigger.itsRrid() = OPTIONAL(v); - } else { - trigger.itsRrid().set_to_omit(); - } - p += 1; - if ((flag & 0x0040) == 0x0040) { - trigger.directionGic() = OPTIONAL(oct2int(OCTETSTRING(1, p))); - } else { - trigger.directionGic().set_to_omit(); - } - p += 1; - if ((flag & 0x0020) == 0x0020) { - trigger.layoutId() = OPTIONAL(oct2int(OCTETSTRING(1, p))); - } else { - trigger.layoutId().set_to_omit(); - } - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: ", trigger); - - // Pass it to the ports if any - to_all_upper_ports(trigger, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_ivim_update(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_ivim_update", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_update: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("ivim") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_update: msg_id=%02x", msg_id); - unsigned char flag = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_update: flag=%02x", flag); - LibItsIvim__TypesAndValues::UtIvimUpdate update; // See ETSI TR 103 099 Cause C.4.1 GenerateIvimEvent - // IviIdentificationNumber - update.iviIdentificationNumber() = oct2int(OCTETSTRING(2, p)); - p += 2; - // validFrom - if ((flag & 0x80) == 0x80) { - update.validFrom() = OPTIONAL(oct2int(OCTETSTRING(6, p))); - } else { - update.validFrom().set_to_omit(); - } - p += 6; - // validTo - if ((flag & 0x40) == 0x40) { - update.validTo() = OPTIONAL(oct2int(OCTETSTRING(6, p))); - } else { - update.validTo().set_to_omit(); - } - p += 6; - // timeStamp - if ((flag & 0x20) == 0x20) { - update.timeStamp() = OPTIONAL(oct2int(OCTETSTRING(6, p))); - } else { - update.timeStamp().set_to_omit(); - } - p += 6; - // connectedIviStructures - if ((flag & 0x01) == 0x01) { - PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; - rov.set_size(*p++); - for (int i = 0; i < rov.size_of(); i++) { - rov[i] = oct2int(OCTETSTRING(4, p)); - p += 4; - } - update.connectedIviStructures() = OPTIONAL(rov); - } else { - update.connectedIviStructures().set_to_omit(); - p += 1; - } - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_ivim_update: ", update); - - // Pass it to the ports if any - to_all_upper_ports(update, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_update: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_ivim_termination(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_ivim_termination"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_termination: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("ivim") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_termination: msg_id=%02x", msg_id); - LibItsIvim__TypesAndValues::UtIvimTermination termination; - termination.iviIdentificationNumber() = oct2int(OCTETSTRING(2, p)); - - // Pass it to the ports if any - to_all_upper_ports(termination, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_termination: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_srem_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_srem_trigger"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("sremssem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id); - LibItsSremSsem__TypesAndValues::UtSremTrigger trigger; // See ETSI TR 103 099 - // BasicVehicleRole - trigger.basicVehicleRole() = oct2int(OCTETSTRING(1, p++)); - // Request Importance Level - trigger.requestImportanceLevel() = oct2int(OCTETSTRING(1, p++)); - // Intersection ID - trigger.intersectionId() = oct2int(OCTETSTRING(1, p++)); - - // Pass it to the ports if any - to_all_upper_ports(trigger, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_srem_update(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_srem_update"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_update: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("sremssem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_update: msg_id=%02x", msg_id); - LibItsSremSsem__TypesAndValues::UtSremUpdate update; // See ETSI TR 103 099 - // RequestID - update.requestID() = oct2int(OCTETSTRING(1, p++)); - // BasicVehicleRole - update.basicVehicleRole() = oct2int(OCTETSTRING(1, p++)); - // Request Importance Level - update.requestImportanceLevel() = oct2int(OCTETSTRING(1, p++)); - - // Pass it to the ports if any - to_all_upper_ports(update, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_update: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_srem_termination(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_srem_termination"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_termination: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("sremssem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_termination: msg_id=%02x", msg_id); - LibItsSremSsem__TypesAndValues::UtSremCancelation termination; // See ETSI TR 103 099 - // RequestID - termination.requestID() = oct2int(OCTETSTRING(1, p++)); - - // Pass it to the ports if any - to_all_upper_ports(termination, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_termination: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("rtcmem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: msg_id=%02x", msg_id); - unsigned char flag = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: flag=%02x", flag); - LibItsRtcmem__TypesAndValues::UtRtcmemTrigger trigger; // See ETSI TR 103 099 Cause C.10.1 GenerateRtcmemEvent - // Decode msgCnt - trigger.msgCnt() = *p++; - // Decode rev - trigger.rev() = DSRC::RTCM__Revision(static_cast(*p++)); - // Decode msgs - DSRC::RTCMmessageList msgs; - unsigned char num_items = *p++; // Number of items - msgs.set_size(num_items); - for (unsigned char i = 0; i < num_items; i++) { - unsigned char len = *p++; // Length of the message - msgs[i] = OCTETSTRING(len, p); - p += len; - } // End of 'for' statement - trigger.msgs() = msgs; - // timeStamp - if ((flag & 0x80) == 0x80) { - // TODO trigger.timeStamp() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - trigger.timeStamp().set_to_omit(); - } - // TODO p += 3; - // anchorPoint - if ((flag & 0x40) == 0x40) { - // TODO trigger.anchorPoint() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - trigger.anchorPoint().set_to_omit(); - } - // TODO p += 3; - // rtcmHeader - if ((flag & 0x20) == 0x20) { - // TODO trigger.rtcmHeader() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - trigger.rtcmHeader().set_to_omit(); - } - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: ", trigger); - - // Pass it to the ports if any - to_all_upper_ports(trigger, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_rtcmem_update(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_rtcmem_update", data); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("rtcmem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: msg_id=%02x", msg_id); - unsigned char flag = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: flag=%02x", flag); - LibItsRtcmem__TypesAndValues::UtRtcmemUpdate update; // See ETSI TR 103 099 Cause C.10.2 GenerateRtcmemUpdate - // Decode msgs - DSRC::RTCMmessageList msgs; - p += 1; // Skip COER flag - unsigned char num_items = *p++; // Number of items - msgs.set_size(num_items); - for (unsigned char i = 0; i < num_items; i++) { - unsigned char len = *p++; // Length of the message - msgs[i] = OCTETSTRING(len, p); - p += len; - } // End of 'for' statement - update.msgs() = msgs; - // ValidityDuration - if ((flag & 0x80) == 0x80) { - // TODO update.timeStamp() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - update.timeStamp().set_to_omit(); - } - // TODO p += 3; - if ((flag & 0x40) == 0x40) { - // TODO update.anchorPoint() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - update.anchorPoint().set_to_omit(); - } - // TODO p += 3; - if ((flag & 0x20) == 0x20) { - // TODO update.rtcmHeader() = OPTIONAL(oct2int(OCTETSTRING(3, p))); - } else { - update.rtcmHeader().set_to_omit(); - } - loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: ", update); - - // Pass it to the ports if any - to_all_upper_ports(update, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: Unsupported protocol"); - return -1; - } - - return 0; -} - -int ConfigRsuSimulatorLayer::process_ut_rtcmem_termination(const OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_rtcmem_termination"); - - params::const_iterator it = _params.find("ut"); - if (it == _params.cend()) { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_termination: CF layer's ut parameter is missing"); - return -1; - } - - if (_params[std::string("ut")].compare("rtcmem") == 0) { - unsigned char *p = (unsigned char *)static_cast(data); - unsigned char msg_id = *p++; - loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_termination: msg_id=%02x", msg_id); - LibItsRtcmem__TypesAndValues::UtRtcmemTermination termination; - termination.msgCnt() = static_cast(*p); - - // Pass it to the ports if any - to_all_upper_ports(termination, params); - } else { - loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_termination: Unsupported protocol"); - return -1; - } - - return 0; -} - -ConfigRsuSimulatorLayerFactory ConfigRsuSimulatorLayerFactory::_f; +#include "ConfigRsuSimulatorLayerFactory.hh" + +#include "loggers.hh" + +#include "ItsRSUsSimulator_TestSystem.hh" + +#include "LibCommon_BasicTypesAndValues.hh" + +#include "UpperTesterRtcmemCodec.hh" +#include "UpperTesterSremSsemCodec.hh" +#include "uppertester_cam_codec.hh" +#include "uppertester_denm_codec.hh" +#include "uppertester_geonetworking_codec.hh" +#include "uppertester_ivim_codec.hh" +#include "uppertester_mapem_spatem_codec.hh" + +#include "LibItsCam_EncdecDeclarations.hh" +#include "LibItsDenm_EncdecDeclarations.hh" +#include "LibItsIvim_EncdecDeclarations.hh" +#include "LibItsMapemSpatem_EncdecDeclarations.hh" +#include "LibItsRtcmem_EncdecDeclarations.hh" +#include "LibItsSremSsem_EncdecDeclarations.hh" + +ConfigRsuSimulatorLayer::ConfigRsuSimulatorLayer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec(), _codec_cam() { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::ConfigRsuSimulatorLayer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); +} + +void ConfigRsuSimulatorLayer::sendMsg(const ItsRSUsSimulator__TestSystem::CfInitialize &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + // Encode ConfigRsuSimulator PDU + OCTETSTRING data; + if (_codec.encode(static_cast(send_par), data) == -1) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Encoding failure"); + return; + } + + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnResults::ALT_utGnInitializeResult)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utGnInitializeResult())); + } else if (send_par.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnResults::ALT_utGnTriggerResult)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTriggerResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utGnTriggerResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtGnResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnEventIndication)); + OCTETSTRING l = int2oct(send_par.rawPayload().lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(send_par.rawPayload().lengthof(), static_cast(send_par.rawPayload())); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsCam__TypesAndValues::UtCamResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsCam__TypesAndValues::UtCamResults::ALT_utCamInitializeResult)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utCamInitializeResult())); + } else if (send_par.ischosen(LibItsCam__TypesAndValues::UtCamResults::ALT_utCamTriggerResult)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamTriggerResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utCamTriggerResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtCamResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsCam__TypesAndValues::UtCamEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamEventInd)); + BITSTRING bs = LibItsCam__EncdecDeclarations::fx__enc__CAM(send_par.camMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmInitializeResult)) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utDenmInitializeResult())); + } else if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmTriggerResult)) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmTriggerResult)); + const LibItsDenm__TypesAndValues::UtDenmTriggerResult &r = send_par.utDenmTriggerResult(); + encoding_buffer.put_c((unsigned char)static_cast(r.result())); + OCTETSTRING os = int2oct(r.actionId().originatingStationID(), 4); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + os = int2oct(r.actionId().sequenceNumber(), 2); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + } else if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmUpdateResult)) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmUpdateResult)); + const LibItsDenm__TypesAndValues::UtDenmUpdateResult &r = send_par.utDenmUpdateResult(); + encoding_buffer.put_c((unsigned char)static_cast(r.result())); + OCTETSTRING os = int2oct(r.actionId().originatingStationID(), 4); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + os = int2oct(r.actionId().sequenceNumber(), 2); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + } else if (send_par.ischosen(LibItsDenm__TypesAndValues::UtDenmResults::ALT_utDenmTerminationResult)) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utDenmTerminationResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtDenmResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmEventIndication)); + BITSTRING bs = LibItsDenm__EncdecDeclarations::fx__enc__DENM(send_par.denMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsPki__TypesAndValues::UtPkiResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsPki__TypesAndValues::UtPkiResults::ALT_utPkiInitializeResult)) { + encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utPkiInitializeResult())); + } else if (send_par.ischosen(LibItsPki__TypesAndValues::UtPkiResults::ALT_utPkiTriggerResult)) { + encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiTriggerResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utPkiTriggerResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtPkiResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimInitializeResult)) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utIvimInitializeResult())); + } else if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimTriggerResult)) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTriggerResult)); + const LibItsIvim__TypesAndValues::UtIvimTriggerResult &r = + dynamic_cast(send_par.utIvimTriggerResult()); + encoding_buffer.put_c((unsigned char)static_cast(r.result())); + OCTETSTRING os = int2oct(r.iviIdentificationNumber(), 2); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + } else if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimUpdateResult)) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimUpdateResult)); + const LibItsIvim__TypesAndValues::UtIvimUpdateResult &r = + dynamic_cast(send_par.utIvimUpdateResult()); + encoding_buffer.put_c((unsigned char)static_cast(r.result())); + OCTETSTRING os = int2oct(r.iviIdentificationNumber(), 2); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + } else if (send_par.ischosen(LibItsIvim__TypesAndValues::UtIvimResults::ALT_utIvimTerminationResult)) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTerminationResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utIvimTerminationResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtIvimResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimEventIndication)); + BITSTRING bs = LibItsIvim__EncdecDeclarations::fx__enc__IVIM(send_par.iviMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults::ALT_utMapemSpatemInitializeResult)) { + encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utMapemSpatemInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utMapemSpatemInitializeResult())); + } else if (send_par.ischosen(LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults::ALT_utMapemSpatemTriggerResult)) { + encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utMapemSpatemTriggerResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utMapemSpatemTriggerResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtMapemSpatemResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utMapemEventIndication)); + BITSTRING bs = LibItsMapemSpatem__EncdecDeclarations::fx__enc__MAPEM(send_par.mapeMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(uppertester_mapem_spatem_codec::c_utSpatemEventIndication)); + BITSTRING bs = LibItsMapemSpatem__EncdecDeclarations::fx__enc__SPATEM(send_par.spateMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremInitializeResult)) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremInitializeResult())); + } else if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremTriggerResult)) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremTriggerResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremTriggerResult())); + } else if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremUpdateResult)) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremUpdateResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremUpdateResult())); + } else if (send_par.ischosen(LibItsSremSsem__TypesAndValues::UtSremResults::ALT_utSremCancelationResult)) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremCancelationResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utSremCancelationResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtSremResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremEventIndication)); + BITSTRING bs = LibItsSremSsem__EncdecDeclarations::fx__enc__SREM(send_par.sreMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSsemEventIndication)); + BITSTRING bs = LibItsSremSsem__EncdecDeclarations::fx__enc__SSEM(send_par.sseMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemInitializeResult)) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemInitializeResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemInitializeResult())); + } else if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemTriggerResult)) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTriggerResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemTriggerResult())); + } else if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemUpdateResult)) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemUpdateResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemUpdateResult())); + } else if (send_par.ischosen(LibItsRtcmem__TypesAndValues::UtRtcmemResults::ALT_utRtcmemTerminationResult)) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTerminationResult)); + encoding_buffer.put_c((unsigned char)static_cast(send_par.utRtcmemTerminationResult())); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::sendMsg: Unsupported UtRtcmemResults variant"); + return; + } + + OCTETSTRING os(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(os, _params); +} + +void ConfigRsuSimulatorLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::sendMsg: ", send_par); + + TTCN_Buffer encoding_buffer; + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemEventIndication)); + BITSTRING bs = LibItsRtcmem__EncdecDeclarations::fx__enc__RTCMEM(send_par.rtcmemMsg()); + OCTETSTRING os = bit2oct(bs); + OCTETSTRING l = int2oct(os.lengthof(), 2); + encoding_buffer.put_s(l.lengthof(), static_cast(l)); + encoding_buffer.put_s(os.lengthof(), static_cast(os)); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + send_data(data, _params); +} + +void ConfigRsuSimulatorLayer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::send_data: ", data); + + send_to_all_layers(data, params); +} + +void ConfigRsuSimulatorLayer::receive_data(OCTETSTRING &data, params ¶ms) { // FIXME To be moved into ConfigRsuSimulatorCodec + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::receive_data: ", data); + + unsigned char id = *(static_cast(data)); + if (id == 0x00) { // Receive an UtxxInitialise + process_utinitialize_data(data, params); + } else if (id == uppertester_cam_codec::c_utCamChangeCurvature) { + process_ut_cam_changecurvature_data(data, params); + } else if (id == uppertester_cam_codec::c_utCamChangeSpeed) { + process_ut_cam_changespeed_data(data, params); + } else if (id == uppertester_cam_codec::c_utCamChangeHeading) { + process_ut_cam_changeheading_data(data, params); + } else if (id == uppertester_cam_codec::c_utCamSetVehicleRole) { + process_ut_cam_setvehiclerole_data(data, params); + } else if (id == uppertester_denm_codec::c_utDenmTrigger) { + process_ut_denm_trigger(data, params); + } else if (id == uppertester_denm_codec::c_utDenmUpdate) { + process_ut_denm_update(data, params); + } else if (id == uppertester_denm_codec::c_utDenmTermination) { + process_ut_denm_termination(data, params); + } else if (id == uppertester_mapem_spatem_codec::c_utMapemSpatemTrigger) { + process_ut_mapem_spatem_trigger(data, params); + } else if (id == uppertester_ivim_codec::c_utIvimTrigger) { + process_ut_ivim_trigger(data, params); + } else if (id == uppertester_ivim_codec::c_utIvimUpdate) { + process_ut_ivim_update(data, params); + } else if (id == uppertester_ivim_codec::c_utIvimTermination) { + process_ut_ivim_termination(data, params); + } else if (id == UpperTesterSremSsemCodec::c_utSremTrigger) { + process_ut_srem_trigger(data, params); + } else if (id == UpperTesterSremSsemCodec::c_utSremUpdate) { + process_ut_srem_update(data, params); + } else if (id == UpperTesterSremSsemCodec::c_utSremCancelation) { + process_ut_srem_termination(data, params); + } else if (id == UpperTesterRtcmemCodec::c_utRtcmemTrigger) { + process_ut_rtcmem_trigger(data, params); + } else if (id == UpperTesterRtcmemCodec::c_utRtcmemUpdate) { + process_ut_rtcmem_update(data, params); + } else if (id == UpperTesterRtcmemCodec::c_utRtcmemTermination) { + process_ut_rtcmem_termination(data, params); + } else if ((id >= uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast) && + (id <= uppertester_geonetworking_codec::c_utGnTrigger_Tsb)) { // Receive an UtGnTrigger + process_ut_geonetworking_trigger(data, params); + } else if ((id == uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest) || + (id == uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest)) { // Receive an UtPkiTrigger + process_ut_pki_trigger(data, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::receive_data: Unsupported tag %02x", id); + } +} + +int ConfigRsuSimulatorLayer::process_utinitialize_data(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_utinitialize_data"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_utinitialize_data: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("gn") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsGeoNetworking__TypesAndValues::UtGnInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("cam") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsCam__TypesAndValues::UtCamInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("denm") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsDenm__TypesAndValues::UtDenmInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("pki") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsPki__TypesAndValues::UtPkiInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("ivim") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsIvim__TypesAndValues::UtIvimInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("mapemspatem") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("sremssem") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsSremSsem__TypesAndValues::UtSremInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else if (_params[std::string("ut")].compare("rtcmem") == 0) { + OCTETSTRING hashedId(data.lengthof() - 1, 1 + static_cast(data)); + LibItsRtcmem__TypesAndValues::UtRtcmemInitialize p(hashedId); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_utinitialize_data: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("cam") == 0) { + OCTETSTRING speed(data.lengthof() - 1, 1 + static_cast(data)); + LibItsCam__TypesAndValues::UtCamTrigger p; + p.changeSpeed() = oct2int(speed); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changespeed_data: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("cam") == 0) { + OCTETSTRING curvature(data.lengthof() - 1, 1 + static_cast(data)); + LibItsCam__TypesAndValues::UtCamTrigger p; + p.changeCurvature() = oct2int(curvature); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changecurvature_data: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("cam") == 0) { + OCTETSTRING heading(data.lengthof() - 1, 1 + static_cast(data)); + LibItsCam__TypesAndValues::UtCamTrigger p; + p.changeHeading() = oct2int(heading); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_changeheading_data: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("cam") == 0) { + OCTETSTRING vehicle_role(data.lengthof() - 1, 1 + static_cast(data)); + LibItsCam__TypesAndValues::UtCamTrigger p; + p.setVehicleRole() = oct2int(vehicle_role); + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_cam_setvehiclerole_data: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_denm_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_denm_trigger", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("denm") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_trigger: msg_id=%02x", msg_id); + unsigned char flag = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_trigger: flag=%02x", flag); + LibItsDenm__TypesAndValues::UtDenmTrigger trigger; // See ETSI TR 103 099 Cause C.4.1 GenerateDenmEvent + // Decode detectionTime + trigger.detectionTime() = oct2int(OCTETSTRING(6, p)); + p += 6; + // ValidityDuration + if ((flag & 0x80) == 0x80) { + trigger.validityDuration() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + trigger.validityDuration().set_to_omit(); + } + p += 3; + if ((flag & 0x40) == 0x40) { + trigger.repetitionDuration() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + trigger.repetitionDuration().set_to_omit(); + } + p += 3; + // Situation + trigger.situation().informationQuality() = oct2int(OCTETSTRING(1, p++)); + trigger.situation().eventType().causeCode() = oct2int(OCTETSTRING(1, p++)); + trigger.situation().eventType().subCauseCode() = oct2int(OCTETSTRING(1, p++)); + trigger.situation().linkedCause().set_to_omit(); + trigger.situation().eventHistory().set_to_omit(); + // RelevanceDistance + trigger.relevanceDistance() = oct2int(OCTETSTRING(1, p++)); + // RelevanceTrafficDirection + trigger.relevanceTrafficDirection() = oct2int(OCTETSTRING(1, p++)); + if ((flag & 0x04) == 0x04) { + trigger.transmissionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); + } else { + trigger.transmissionInterval().set_to_omit(); + } + p += 2; + if ((flag & 0x02) == 0x02) { + trigger.repetitionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); + } else { + trigger.repetitionInterval().set_to_omit(); + } + p += 2; + // alacarteLength + INTEGER alacarte_length = oct2int(OCTETSTRING(1, p)); + if (static_cast(alacarte_length) != 0) { + p += 1; + // FIXME AlacarteContainer alacarte optional + } else { + trigger.alacarte().set_to_omit(); + } + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_denm_trigger: ", trigger); + + // Pass it to the ports if any + to_all_upper_ports(trigger, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_denm_update(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_denm_update", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_update: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("denm") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_update: msg_id=%02x", msg_id); + unsigned char flag = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_update: flag=%02x", flag); + LibItsDenm__TypesAndValues::UtDenmUpdate update; // See ETSI TR 103 099 Cause C.4.1 GenerateDenmEvent + // Statuion ID + update.actionId().originatingStationID() = oct2int(OCTETSTRING(4, p)); + p += 4; + // SequenceNumber + update.actionId().sequenceNumber() = oct2int(OCTETSTRING(2, p)); + p += 2; + // Decode detectionTime + update.detectionTime() = oct2int(OCTETSTRING(6, p)); + p += 6; + if ((flag & 0x80) == 0x80) { + update.validityDuration() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + update.validityDuration().set_to_omit(); + } + p += 3; + // Situation + if ((flag & 0x40) == 0x40) { + DENM__PDU__Descriptions::SituationContainer &s = static_cast(*update.get_opt_value()); + s.informationQuality() = oct2int(OCTETSTRING(1, p++)); + s.eventType().causeCode() = oct2int(OCTETSTRING(1, p++)); + s.eventType().subCauseCode() = oct2int(OCTETSTRING(1, p++)); + s.linkedCause().set_to_omit(); + s.eventHistory().set_to_omit(); + update.situation() = OPTIONAL(s); + } else { + update.situation().set_to_omit(); + } + // Location + update.location().set_to_omit(); + // RelevanceDistance + if ((flag & 0x20) == 0x20) { + update.relevanceDistance() = oct2int(OCTETSTRING(1, p++)); + } else { + update.relevanceDistance().set_to_omit(); + } + // RelevanceTrafficDirection + if ((flag & 0x10) == 0x10) { + update.relevanceTrafficDirection() = oct2int(OCTETSTRING(1, p++)); + } else { + update.relevanceTrafficDirection().set_to_omit(); + } + if ((flag & 0x08) == 0x08) { + update.transmissionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); + } else { + update.transmissionInterval().set_to_omit(); + } + p += 2; + if ((flag & 0x04) == 0x04) { + update.repetitionInterval() = OPTIONAL(oct2int(OCTETSTRING(2, p))); + } else { + update.repetitionInterval().set_to_omit(); + } + p += 2; + // alacarteLength + INTEGER alacarte_length = oct2int(OCTETSTRING(1, p)); + if (static_cast(alacarte_length) != 0) { + p += 1; + // FIXME AlacarteContainer alacarte optional + } else { + update.alacarte().set_to_omit(); + } + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_denm_update: ", update); + + // Pass it to the ports if any + to_all_upper_ports(update, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_update: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_denm_termination(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_denm_termination"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_termination: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("denm") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_denm_termination: msg_id=%02x", msg_id); + LibItsDenm__TypesAndValues::UtDenmTermination termination; + termination.actionId().originatingStationID() = oct2int(OCTETSTRING(4, p)); + p += 4; + termination.actionId().sequenceNumber() = oct2int(OCTETSTRING(2, p)); + + // Pass it to the ports if any + to_all_upper_ports(termination, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_denm_termination: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("gn") == 0) { + unsigned char msg_id = *static_cast(data); + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id); + OCTETSTRING payload(data.lengthof() - 1, 1 + static_cast(data)); + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: payload:", payload); + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(payload); + + LibItsGeoNetworking__TypesAndValues::UtGnTrigger p; + if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast) { + LibItsGeoNetworking__TypesAndValues::GenerateGeoUnicastMessage g; + g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + if (g.payload().lengthof() > 2) { + g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); + } else { + g.payload() = OCTETSTRING(0, nullptr); + } + p.geoUnicast() = g; + } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast) { + LibItsGeoNetworking__TypesAndValues::GenerateGeoBroadcastMessage g; + g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + if (g.payload().lengthof() > 2) { + g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); + } else { + g.payload() = OCTETSTRING(0, nullptr); + } + p.geoBroadcast() = g; + } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_GeoAnycast) { + LibItsGeoNetworking__TypesAndValues::GenerateGeoAnycastMessage g; + g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + if (g.payload().lengthof() > 2) { + g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); + } else { + g.payload() = OCTETSTRING(0, nullptr); + } + p.geoAnycast() = g; + } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_Shb) { + LibItsGeoNetworking__TypesAndValues::GenerateSHBMessage g; + g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + if (g.payload().lengthof() > 2) { + g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); + } else { + g.payload() = OCTETSTRING(0, nullptr); + } + p.shb() = g; + } else if (msg_id == uppertester_geonetworking_codec::c_utGnTrigger_Tsb) { + LibItsGeoNetworking__TypesAndValues::GenerateTSBMessage g; + g.decode(*g.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + if (g.payload().lengthof() > 2) { + g.payload() = OCTETSTRING(g.payload().lengthof() - 2, static_cast(g.payload())); + } else { + g.payload() = OCTETSTRING(0, nullptr); + } + p.tsb() = g; + } + + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_pki_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_pki_trigger"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_pki_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("pki") == 0) { + unsigned char msg_id = *static_cast(data); + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id); + OCTETSTRING payload(data.lengthof() - 1, 1 + static_cast(data)); + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: payload:", payload); + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(payload); + + LibItsPki__TypesAndValues::UtPkiTrigger p; + if (msg_id == uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest) { + // LibItsPki__TypesAndValues::TriggerEnrolmentRequest e; + // e.decode(*e.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + // p.triggerEnrolmentRequest() = e; + p.triggerEnrolmentRequest().cannonicalId() = OCTETSTRING(0, nullptr); // No parameter used + p.triggerEnrolmentRequest().encAlgorithm() = OCTETSTRING(0, nullptr); // No parameter used + p.triggerEnrolmentRequest().privateKey() = OCTETSTRING(0, nullptr); // No parameter used + p.triggerEnrolmentRequest().compressedPublickey() = OCTETSTRING(0, nullptr); // No parameter used + } else if (msg_id == uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest) { + // LibItsPki__TypesAndValues::TriggerAuthorizationRequest e; + // e.decode(*e.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_RAW); + // p.triggerAuthorizationRequest() = e; + p.triggerAuthorizationRequest().cannonicalId() = OCTETSTRING(0, nullptr); // No parameter used + p.triggerAuthorizationRequest().encAlgorithm() = OCTETSTRING(0, nullptr); // No parameter used + p.triggerAuthorizationRequest().privateKey() = OCTETSTRING(0, nullptr); // No parameter used + p.triggerAuthorizationRequest().compressedPublickey() = OCTETSTRING(0, nullptr); // No parameter used + } + + // Pass it to the ports if any + to_all_upper_ports(p, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_pki_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("mapemspatem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: msg_id=%02x", msg_id); + unsigned char flag = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: flag=%02x", flag); + LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger trigger; // See ETSI TR 103 099 Cause C.4.1 GenerateMapemSpatemEvent + // Decode Event + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: event=%02x", *p); + trigger.event().int2enum(static_cast(*p++)); + // Decode IntersectionId + if ((flag & 0x80) == 0x80) { + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: intersectionID=%04x", (short)*p); + trigger.intersectionID() = OPTIONAL(static_cast((*p << 8) | *(p + 1))); + } else { + trigger.intersectionID().set_to_omit(); + } + p += 2; + // Decode RegulatorySpeedLimit + if ((flag & 0x40) == 0x40) { + DSRC__REGION__noCircular::RegulatorySpeedLimit r; + r.type__().int2enum(static_cast(*p++)); + r.speed() = static_cast((*p << 8) | *(p + 1)); + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: RegulatorySpeedLimit: ", r); + trigger.regulatorySpeedLimit() = OPTIONAL(r); + } else { + trigger.regulatorySpeedLimit().set_to_omit(); + } + p += 2; + // FIXME Add flags + // trigger.latitude().set_to_omit(); + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: ", trigger); + + // Pass it to the ports if any + to_all_upper_ports(trigger, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_mapem_spatem_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_ivim_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_ivim_trigger", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("ivim") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: msg_id=%02x", msg_id); + unsigned short flag = static_cast((*p++) << 8 | (*p++)); + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: flag=%02x", flag); + LibItsIvim__TypesAndValues::UtIvimTrigger trigger; // See ETSI TR 103 099 Cause C.4.1 GenerateIvimEvent + // Decode ValidityFrom + if ((flag & 0x8000) == 0x8000) { + trigger.validFrom() = OPTIONAL(oct2int(OCTETSTRING(6, p))); + } else { + trigger.validFrom().set_to_omit(); + } + p += 6; + // Decode ValidityTo + if ((flag & 0x4000) == 0x4000) { + trigger.validTo() = OPTIONAL(oct2int(OCTETSTRING(6, p))); + } else { + trigger.validTo().set_to_omit(); + } + p += 6; + // Decode RepetitionInterval + if ((flag & 0x2000) == 0x2000) { + trigger.repetitionInterval() = OPTIONAL(oct2int(OCTETSTRING(6, p))); + } else { + trigger.repetitionInterval().set_to_omit(); + } + p += 6; + // Decode zoneIds + if ((flag & 0x1000) == 0x1000) { + PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; + rov.set_size(*p++); + for (int i = 0; i < rov.size_of(); i++) { + rov[i] = oct2int(OCTETSTRING(1, p++)); + } + trigger.zoneIds() = OPTIONAL(rov); + } else { + trigger.zoneIds().set_to_omit(); + p += 1; + } + // Decode laneNumber + if ((flag & 0x0800) == 0x0800) { + trigger.laneNumber() = OPTIONAL(oct2int(OCTETSTRING(1, p))); + } else { + trigger.laneNumber().set_to_omit(); + } + p += 1; + // Decode relavanceZoneIds + if ((flag & 0x0400) == 0x0400) { + PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; + rov.set_size(*p++); + for (int i = 0; i < rov.size_of(); i++) { + rov[i] = oct2int(OCTETSTRING(1, p++)); + } + trigger.relavanceZoneIds() = OPTIONAL(rov); + } else { + trigger.relavanceZoneIds().set_to_omit(); + p += 1; + } + // Decode detectionZoneIds + if ((flag & 0x0200) == 0x0200) { + PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; + rov.set_size(*p++); + for (int i = 0; i < rov.size_of(); i++) { + rov[i] = oct2int(OCTETSTRING(1, p++)); + } + trigger.detectionZoneIds() = OPTIONAL(rov); + } else { + trigger.detectionZoneIds().set_to_omit(); + p += 1; + } + // Decode driverAwarenesZoneIds + if ((flag & 0x0100) == 0x0100) { + PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; + rov.set_size(*p++); + for (int i = 0; i < rov.size_of(); i++) { + rov[i] = oct2int(OCTETSTRING(1, p++)); + } + trigger.driverAwarenesZoneIds() = OPTIONAL(rov); + } else { + trigger.driverAwarenesZoneIds().set_to_omit(); + p += 1; + } + if ((flag & 0x0080) == 0x0080) { + CITSapplMgmtIDs::VarLengthNumber v; + v.content() = oct2int(OCTETSTRING(1, p)); + trigger.itsRrid() = OPTIONAL(v); + } else { + trigger.itsRrid().set_to_omit(); + } + p += 1; + if ((flag & 0x0040) == 0x0040) { + trigger.directionGic() = OPTIONAL(oct2int(OCTETSTRING(1, p))); + } else { + trigger.directionGic().set_to_omit(); + } + p += 1; + if ((flag & 0x0020) == 0x0020) { + trigger.layoutId() = OPTIONAL(oct2int(OCTETSTRING(1, p))); + } else { + trigger.layoutId().set_to_omit(); + } + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: ", trigger); + + // Pass it to the ports if any + to_all_upper_ports(trigger, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_ivim_update(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_ivim_update", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_update: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("ivim") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_update: msg_id=%02x", msg_id); + unsigned char flag = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_update: flag=%02x", flag); + LibItsIvim__TypesAndValues::UtIvimUpdate update; // See ETSI TR 103 099 Cause C.4.1 GenerateIvimEvent + // IviIdentificationNumber + update.iviIdentificationNumber() = oct2int(OCTETSTRING(2, p)); + p += 2; + // validFrom + if ((flag & 0x80) == 0x80) { + update.validFrom() = OPTIONAL(oct2int(OCTETSTRING(6, p))); + } else { + update.validFrom().set_to_omit(); + } + p += 6; + // validTo + if ((flag & 0x40) == 0x40) { + update.validTo() = OPTIONAL(oct2int(OCTETSTRING(6, p))); + } else { + update.validTo().set_to_omit(); + } + p += 6; + // timeStamp + if ((flag & 0x20) == 0x20) { + update.timeStamp() = OPTIONAL(oct2int(OCTETSTRING(6, p))); + } else { + update.timeStamp().set_to_omit(); + } + p += 6; + // connectedIviStructures + if ((flag & 0x01) == 0x01) { + PreGenRecordOf::PREGEN__RECORD__OF__INTEGER rov; + rov.set_size(*p++); + for (int i = 0; i < rov.size_of(); i++) { + rov[i] = oct2int(OCTETSTRING(4, p)); + p += 4; + } + update.connectedIviStructures() = OPTIONAL(rov); + } else { + update.connectedIviStructures().set_to_omit(); + p += 1; + } + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_ivim_update: ", update); + + // Pass it to the ports if any + to_all_upper_ports(update, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_update: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_ivim_termination(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_ivim_termination"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_termination: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("ivim") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_ivim_termination: msg_id=%02x", msg_id); + LibItsIvim__TypesAndValues::UtIvimTermination termination; + termination.iviIdentificationNumber() = oct2int(OCTETSTRING(2, p)); + + // Pass it to the ports if any + to_all_upper_ports(termination, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_ivim_termination: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_srem_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_srem_trigger"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("sremssem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_trigger: msg_id=%02x", msg_id); + LibItsSremSsem__TypesAndValues::UtSremTrigger trigger; // See ETSI TR 103 099 + // BasicVehicleRole + trigger.basicVehicleRole() = oct2int(OCTETSTRING(1, p++)); + // Request Importance Level + trigger.requestImportanceLevel() = oct2int(OCTETSTRING(1, p++)); + // Intersection ID + trigger.intersectionId() = oct2int(OCTETSTRING(1, p++)); + + // Pass it to the ports if any + to_all_upper_ports(trigger, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_srem_update(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_srem_update"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_update: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("sremssem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_update: msg_id=%02x", msg_id); + LibItsSremSsem__TypesAndValues::UtSremUpdate update; // See ETSI TR 103 099 + // RequestID + update.requestID() = oct2int(OCTETSTRING(1, p++)); + // BasicVehicleRole + update.basicVehicleRole() = oct2int(OCTETSTRING(1, p++)); + // Request Importance Level + update.requestImportanceLevel() = oct2int(OCTETSTRING(1, p++)); + + // Pass it to the ports if any + to_all_upper_ports(update, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_update: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_srem_termination(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_srem_termination"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_termination: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("sremssem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_geonetworking_termination: msg_id=%02x", msg_id); + LibItsSremSsem__TypesAndValues::UtSremCancelation termination; // See ETSI TR 103 099 + // RequestID + termination.requestID() = oct2int(OCTETSTRING(1, p++)); + + // Pass it to the ports if any + to_all_upper_ports(termination, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_srem_termination: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("rtcmem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: msg_id=%02x", msg_id); + unsigned char flag = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: flag=%02x", flag); + LibItsRtcmem__TypesAndValues::UtRtcmemTrigger trigger; // See ETSI TR 103 099 Cause C.10.1 GenerateRtcmemEvent + // Decode msgCnt + trigger.msgCnt() = *p++; + // Decode rev + trigger.rev() = DSRC::RTCM__Revision(static_cast(*p++)); + // Decode msgs + DSRC::RTCMmessageList msgs; + unsigned char num_items = *p++; // Number of items + msgs.set_size(num_items); + for (unsigned char i = 0; i < num_items; i++) { + unsigned char len = *p++; // Length of the message + msgs[i] = OCTETSTRING(len, p); + p += len; + } // End of 'for' statement + trigger.msgs() = msgs; + // timeStamp + if ((flag & 0x80) == 0x80) { + // TODO trigger.timeStamp() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + trigger.timeStamp().set_to_omit(); + } + // TODO p += 3; + // anchorPoint + if ((flag & 0x40) == 0x40) { + // TODO trigger.anchorPoint() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + trigger.anchorPoint().set_to_omit(); + } + // TODO p += 3; + // rtcmHeader + if ((flag & 0x20) == 0x20) { + // TODO trigger.rtcmHeader() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + trigger.rtcmHeader().set_to_omit(); + } + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: ", trigger); + + // Pass it to the ports if any + to_all_upper_ports(trigger, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_trigger: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_rtcmem_update(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorLayer::process_ut_rtcmem_update", data); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("rtcmem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: msg_id=%02x", msg_id); + unsigned char flag = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: flag=%02x", flag); + LibItsRtcmem__TypesAndValues::UtRtcmemUpdate update; // See ETSI TR 103 099 Cause C.10.2 GenerateRtcmemUpdate + // Decode msgs + DSRC::RTCMmessageList msgs; + p += 1; // Skip COER flag + unsigned char num_items = *p++; // Number of items + msgs.set_size(num_items); + for (unsigned char i = 0; i < num_items; i++) { + unsigned char len = *p++; // Length of the message + msgs[i] = OCTETSTRING(len, p); + p += len; + } // End of 'for' statement + update.msgs() = msgs; + // ValidityDuration + if ((flag & 0x80) == 0x80) { + // TODO update.timeStamp() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + update.timeStamp().set_to_omit(); + } + // TODO p += 3; + if ((flag & 0x40) == 0x40) { + // TODO update.anchorPoint() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + update.anchorPoint().set_to_omit(); + } + // TODO p += 3; + if ((flag & 0x20) == 0x20) { + // TODO update.rtcmHeader() = OPTIONAL(oct2int(OCTETSTRING(3, p))); + } else { + update.rtcmHeader().set_to_omit(); + } + loggers::get_instance().log_msg("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: ", update); + + // Pass it to the ports if any + to_all_upper_ports(update, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_update: Unsupported protocol"); + return -1; + } + + return 0; +} + +int ConfigRsuSimulatorLayer::process_ut_rtcmem_termination(const OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> ConfigRsuSimulatorLayer::process_ut_rtcmem_termination"); + + params::const_iterator it = _params.find("ut"); + if (it == _params.cend()) { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_termination: CF layer's ut parameter is missing"); + return -1; + } + + if (_params[std::string("ut")].compare("rtcmem") == 0) { + unsigned char *p = (unsigned char *)static_cast(data); + unsigned char msg_id = *p++; + loggers::get_instance().log("ConfigRsuSimulatorLayer::process_ut_rtcmem_termination: msg_id=%02x", msg_id); + LibItsRtcmem__TypesAndValues::UtRtcmemTermination termination; + termination.msgCnt() = static_cast(*p); + + // Pass it to the ports if any + to_all_upper_ports(termination, params); + } else { + loggers::get_instance().warning("ConfigRsuSimulatorLayer::process_ut_rtcmem_termination: Unsupported protocol"); + return -1; + } + + return 0; +} + +ConfigRsuSimulatorLayerFactory ConfigRsuSimulatorLayerFactory::_f; diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.hh b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.hh index 900a53301231c0701aa24c60519155a3deca8e54..9e2dfcf3aafa8b209bfa2c882274d0681e5e758b 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.hh +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayer.hh @@ -1,82 +1,82 @@ -/*! - * \file ConfigRsuSimulatorLayer.hh - * \brief Header file for ITS Configuration port protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "ConfigRsuSimulatorCodec.hh" -#include "UpperTesterRtcmemCodec.hh" -#include "UpperTesterSremSsemCodec.hh" -#include "t_layer.hh" -#include "uppertester_cam_codec.hh" -#include "uppertester_denm_codec.hh" -#include "uppertester_geonetworking_codec.hh" -#include "uppertester_ivim_codec.hh" -#include "uppertester_mapem_spatem_codec.hh" -#include "uppertester_pki_codec.hh" - -namespace ItsRSUsSimulator__TestSystem { - class ConfigRsuSimulatorPort; - class CfInitialize; -} // namespace ItsRSUsSimulator__TestSystem - -class ConfigRsuSimulatorLayer : public t_layer { - params _params; - ConfigRsuSimulatorCodec _codec; - uppertester_cam_codec _codec_cam; // FIXME Enhance all codec to encode inputs messages also - -public: - ConfigRsuSimulatorLayer() : t_layer(), _params(), _codec(), _codec_cam(){}; - ConfigRsuSimulatorLayer(const std::string &p_type, const std::string ¶m); - virtual ~ConfigRsuSimulatorLayer(){}; - - void sendMsg(const ItsRSUsSimulator__TestSystem::CfInitialize &, params ¶ms); - void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par, params ¶ms); - void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par, params ¶ms); - void sendMsg(const LibItsCam__TypesAndValues::UtCamResults &send_par, params ¶ms); - void sendMsg(const LibItsCam__TypesAndValues::UtCamEventInd &send_par, params ¶ms); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmResults &send_par, params ¶ms); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par, params ¶ms); - void sendMsg(const LibItsPki__TypesAndValues::UtPkiResults &send_par, params ¶ms); - void sendMsg(const LibItsIvim__TypesAndValues::UtIvimResults &send_par, params ¶ms); - void sendMsg(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par, params ¶ms); - void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par, params ¶ms); - void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par, params ¶ms); - void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par, params ¶ms); - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par, params ¶ms); - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par, params ¶ms); - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par, params ¶ms); - void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par, params ¶ms); - void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par, params ¶ms); - - virtual void send_data(OCTETSTRING &data, params ¶ms); - virtual void receive_data(OCTETSTRING &data, params ¶ms); - -private: - int process_utinitialize_data(const OCTETSTRING &data, params ¶ms); - int process_ut_cam_changespeed_data(const OCTETSTRING &data, params ¶ms); - int process_ut_cam_changecurvature_data(const OCTETSTRING &data, params ¶ms); - int process_ut_cam_changeheading_data(const OCTETSTRING &data, params ¶ms); - int process_ut_cam_setvehiclerole_data(const OCTETSTRING &data, params ¶ms); - int process_ut_denm_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_denm_update(const OCTETSTRING &data, params ¶ms); - int process_ut_denm_termination(const OCTETSTRING &data, params ¶ms); - int process_ut_geonetworking_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_pki_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_ivim_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_ivim_update(const OCTETSTRING &data, params ¶ms); - int process_ut_ivim_termination(const OCTETSTRING &data, params ¶ms); - int process_ut_mapem_spatem_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_srem_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_srem_update(const OCTETSTRING &data, params ¶ms); - int process_ut_srem_termination(const OCTETSTRING &data, params ¶ms); - int process_ut_rtcmem_trigger(const OCTETSTRING &data, params ¶ms); - int process_ut_rtcmem_update(const OCTETSTRING &data, params ¶ms); - int process_ut_rtcmem_termination(const OCTETSTRING &data, params ¶ms); -}; // End of class ConfigRsuSimulatorLayer +/*! + * \file ConfigRsuSimulatorLayer.hh + * \brief Header file for ITS Configuration port protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "ConfigRsuSimulatorCodec.hh" +#include "UpperTesterRtcmemCodec.hh" +#include "UpperTesterSremSsemCodec.hh" +#include "t_layer.hh" +#include "uppertester_cam_codec.hh" +#include "uppertester_denm_codec.hh" +#include "uppertester_geonetworking_codec.hh" +#include "uppertester_ivim_codec.hh" +#include "uppertester_mapem_spatem_codec.hh" +#include "uppertester_pki_codec.hh" + +namespace ItsRSUsSimulator__TestSystem { + class ConfigRsuSimulatorPort; + class CfInitialize; +} // namespace ItsRSUsSimulator__TestSystem + +class ConfigRsuSimulatorLayer : public t_layer { + params _params; + ConfigRsuSimulatorCodec _codec; + uppertester_cam_codec _codec_cam; // FIXME Enhance all codec to encode inputs messages also + +public: + ConfigRsuSimulatorLayer() : t_layer(), _params(), _codec(), _codec_cam(){}; + ConfigRsuSimulatorLayer(const std::string &p_type, const std::string ¶m); + virtual ~ConfigRsuSimulatorLayer(){}; + + void sendMsg(const ItsRSUsSimulator__TestSystem::CfInitialize &, params ¶ms); + void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par, params ¶ms); + void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par, params ¶ms); + void sendMsg(const LibItsCam__TypesAndValues::UtCamResults &send_par, params ¶ms); + void sendMsg(const LibItsCam__TypesAndValues::UtCamEventInd &send_par, params ¶ms); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmResults &send_par, params ¶ms); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par, params ¶ms); + void sendMsg(const LibItsPki__TypesAndValues::UtPkiResults &send_par, params ¶ms); + void sendMsg(const LibItsIvim__TypesAndValues::UtIvimResults &send_par, params ¶ms); + void sendMsg(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par, params ¶ms); + void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par, params ¶ms); + void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par, params ¶ms); + void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par, params ¶ms); + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par, params ¶ms); + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par, params ¶ms); + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par, params ¶ms); + void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par, params ¶ms); + void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par, params ¶ms); + + virtual void send_data(OCTETSTRING &data, params ¶ms); + virtual void receive_data(OCTETSTRING &data, params ¶ms); + +private: + int process_utinitialize_data(const OCTETSTRING &data, params ¶ms); + int process_ut_cam_changespeed_data(const OCTETSTRING &data, params ¶ms); + int process_ut_cam_changecurvature_data(const OCTETSTRING &data, params ¶ms); + int process_ut_cam_changeheading_data(const OCTETSTRING &data, params ¶ms); + int process_ut_cam_setvehiclerole_data(const OCTETSTRING &data, params ¶ms); + int process_ut_denm_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_denm_update(const OCTETSTRING &data, params ¶ms); + int process_ut_denm_termination(const OCTETSTRING &data, params ¶ms); + int process_ut_geonetworking_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_pki_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_ivim_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_ivim_update(const OCTETSTRING &data, params ¶ms); + int process_ut_ivim_termination(const OCTETSTRING &data, params ¶ms); + int process_ut_mapem_spatem_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_srem_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_srem_update(const OCTETSTRING &data, params ¶ms); + int process_ut_srem_termination(const OCTETSTRING &data, params ¶ms); + int process_ut_rtcmem_trigger(const OCTETSTRING &data, params ¶ms); + int process_ut_rtcmem_update(const OCTETSTRING &data, params ¶ms); + int process_ut_rtcmem_termination(const OCTETSTRING &data, params ¶ms); +}; // End of class ConfigRsuSimulatorLayer diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayerFactory.hh b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayerFactory.hh index 399ddf80bbb8612c379696adbdc6197f067d64f3..108bb4a593f83b997dfc4de20c4b381cb85bd43b 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayerFactory.hh +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorLayerFactory.hh @@ -1,28 +1,28 @@ -/*! - * \file ConfigRsuSimulatorLayerFactory.hh - * \brief Header file for ITS ConfigRsuSimulator protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "ConfigRsuSimulatorLayer.hh" - -class ConfigRsuSimulatorLayerFactory : public layer_factory { - static ConfigRsuSimulatorLayerFactory _f; - -public: - ConfigRsuSimulatorLayerFactory() { - // Register factory - layer_stack_builder::register_layer_factory("CF", this); - }; - - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new ConfigRsuSimulatorLayer(p_type, p_param); }; - -}; // End of class ConfigRsuSimulatorLayerFactory +/*! + * \file ConfigRsuSimulatorLayerFactory.hh + * \brief Header file for ITS ConfigRsuSimulator protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "ConfigRsuSimulatorLayer.hh" + +class ConfigRsuSimulatorLayerFactory : public layer_factory { + static ConfigRsuSimulatorLayerFactory _f; + +public: + ConfigRsuSimulatorLayerFactory() { + // Register factory + layer_stack_builder::register_layer_factory("CF", this); + }; + + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new ConfigRsuSimulatorLayer(p_type, p_param); }; + +}; // End of class ConfigRsuSimulatorLayerFactory diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.cc b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.cc index 45b2846abcb60102fb14cf84bfde3349623b1554..dbd5e5428e0ac44f29c8f54db53bd38ea5e0504c 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.cc +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.cc @@ -1,487 +1,487 @@ -#include "ConfigRsuSimulatorPort.hh" -#include "ConfigRsuSimulatorLayerFactory.hh" -#include "loggers.hh" - -namespace ItsRSUsSimulator__TestSystem { - - ConfigRsuSimulatorPort::ConfigRsuSimulatorPort(const char *par_port_name) - : ConfigRsuSimulatorPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(nullptr), _time_key("ConfigRsuSimulatorPort::outgoing_send") { - // Nothing to do - } // End of constructor - - ConfigRsuSimulatorPort::~ConfigRsuSimulatorPort() { - loggers::get_instance().log(">>> ConfigRsuSimulatorPort::~ConfigRsuSimulatorPort"); - - if (_layer != nullptr) { - delete _layer; - } - } // End of destructor - - void ConfigRsuSimulatorPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("ConfigRsuSimulatorPort::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - } - - /*void ConfigRsuSimulatorPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void ConfigRsuSimulatorPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void ConfigRsuSimulatorPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void ConfigRsuSimulatorPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void ConfigRsuSimulatorPort::Handle_Timeout(double time_since_last_call) {}*/ - - void ConfigRsuSimulatorPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("ConfigRsuSimulatorPort::user_map: %s", it->second.c_str()); - // Setup parameters - params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless - // Create layer - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == nullptr) { - loggers::get_instance().error("ConfigRsuSimulatorPort::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - - } else { - loggers::get_instance().error("ConfigRsuSimulatorPort::user_map: No layers defined in configuration file"); - } - } // End of user_map method - - void ConfigRsuSimulatorPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_unmap: %s", system_port); - - // Reset layers - if (_layer != nullptr) { - delete _layer; - _layer = nullptr; - } - } // End of user_unmap method - - void ConfigRsuSimulatorPort::user_start() { loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_start"); } // End of user_start method - - void ConfigRsuSimulatorPort::user_stop() { loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_stop"); } // End of user_stop method - - void ConfigRsuSimulatorPort::outgoing_send(const CfInitialize &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - /*float duration; - loggers::get_instance().set_start_time(_time_key); - params params; - static_cast(_layer)->sendMsg(send_par, params); - loggers::get_instance().set_stop_time(_time_key, duration);*/ - } - - void ConfigRsuSimulatorPort::outgoing_send(const BOOLEAN &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsPki__TypesAndValues::UtPkiResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void ConfigRsuSimulatorPort::receiveMsg(const BOOLEAN &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - // incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsCam__TypesAndValues::UtCamInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsCam__TypesAndValues::UtCamTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - - void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - incoming_message(p_ind); - } - -} // namespace ItsRSUsSimulator__TestSystem +#include "ConfigRsuSimulatorPort.hh" +#include "ConfigRsuSimulatorLayerFactory.hh" +#include "loggers.hh" + +namespace ItsRSUsSimulator__TestSystem { + + ConfigRsuSimulatorPort::ConfigRsuSimulatorPort(const char *par_port_name) + : ConfigRsuSimulatorPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(nullptr), _time_key("ConfigRsuSimulatorPort::outgoing_send") { + // Nothing to do + } // End of constructor + + ConfigRsuSimulatorPort::~ConfigRsuSimulatorPort() { + loggers::get_instance().log(">>> ConfigRsuSimulatorPort::~ConfigRsuSimulatorPort"); + + if (_layer != nullptr) { + delete _layer; + } + } // End of destructor + + void ConfigRsuSimulatorPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("ConfigRsuSimulatorPort::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + } + + /*void ConfigRsuSimulatorPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void ConfigRsuSimulatorPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void ConfigRsuSimulatorPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void ConfigRsuSimulatorPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void ConfigRsuSimulatorPort::Handle_Timeout(double time_since_last_call) {}*/ + + void ConfigRsuSimulatorPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("ConfigRsuSimulatorPort::user_map: %s", it->second.c_str()); + // Setup parameters + params::convert(_layer_params, it->second); // TODO This _layer_params seems to be useless + // Create layer + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == nullptr) { + loggers::get_instance().error("ConfigRsuSimulatorPort::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + + } else { + loggers::get_instance().error("ConfigRsuSimulatorPort::user_map: No layers defined in configuration file"); + } + } // End of user_map method + + void ConfigRsuSimulatorPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_unmap: %s", system_port); + + // Reset layers + if (_layer != nullptr) { + delete _layer; + _layer = nullptr; + } + } // End of user_unmap method + + void ConfigRsuSimulatorPort::user_start() { loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_start"); } // End of user_start method + + void ConfigRsuSimulatorPort::user_stop() { loggers::get_instance().log(">>> ConfigRsuSimulatorPort::user_stop"); } // End of user_stop method + + void ConfigRsuSimulatorPort::outgoing_send(const CfInitialize &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + /*float duration; + loggers::get_instance().set_start_time(_time_key); + params params; + static_cast(_layer)->sendMsg(send_par, params); + loggers::get_instance().set_stop_time(_time_key, duration);*/ + } + + void ConfigRsuSimulatorPort::outgoing_send(const BOOLEAN &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsCam__TypesAndValues::UtCamEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsPki__TypesAndValues::UtPkiResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::outgoing_send: payload=", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void ConfigRsuSimulatorPort::receiveMsg(const BOOLEAN &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + // incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsCam__TypesAndValues::UtCamInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsCam__TypesAndValues::UtCamTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + + void ConfigRsuSimulatorPort::receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> ConfigRsuSimulatorPort::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + incoming_message(p_ind); + } + +} // namespace ItsRSUsSimulator__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.hh b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.hh index bb01aafc04c120c00e8db40248c56ffebf69866d..d691e51d970b2f55d473db676f1b03bb1d37579c 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.hh +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/ConfigRsuSimulatorPort.hh @@ -1,96 +1,96 @@ -#pragma once - -#include "ItsRSUsSimulator_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace ItsRSUsSimulator__TestSystem { - - class ConfigRsuSimulatorPort : public ConfigRsuSimulatorPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - ConfigRsuSimulatorPort(const char *par_port_name); - ~ConfigRsuSimulatorPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const BOOLEAN &p_ind, const params &p_params); - void receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsCam__TypesAndValues::UtCamInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsCam__TypesAndValues::UtCamTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &p_ind, const params &p_params); - void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &p_ind, const params &p_params); - void receiveMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &p_ind, const params &p_params); - void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &p_ind, const params &p_params); - void receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &p_ind, const params &p_params); - void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &p_ind, const params &p_params); - void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &p_ind, const params &p_params); - void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &p_ind, const params &p_params); - void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &p_ind, const params &p_params); - void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &p_ind, const params &p_params); - - /*void send(const CfInitialize& send_par, const COMPONENT& destination_component); - void send(const CfInitialize& send_par); - void send(const CfInitialize_template& send_par, const COMPONENT& destination_component); - void send(const CfInitialize_template& send_par); - void send(const BOOLEAN& send_par, const COMPONENT& destination_component); - void send(const BOOLEAN& send_par); - void send(const BOOLEAN_template& send_par, const COMPONENT& destination_component); - void send(const BOOLEAN_template& send_par); - void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults& send_par, const COMPONENT& destination_component); - void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults& send_par); - void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults_template& send_par, const COMPONENT& destination_component); - void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults_template& send_par);*/ - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const CfInitialize &send_par); - void outgoing_send(const BOOLEAN &send_par); - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par); - void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par); - void outgoing_send(const LibItsCam__TypesAndValues::UtCamResults &send_par); - void outgoing_send(const LibItsCam__TypesAndValues::UtCamEventInd &send_par); - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmResults &send_par); - void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par); - void outgoing_send(const LibItsPki__TypesAndValues::UtPkiResults &send_par); - void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimResults &send_par); - void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par); - void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par); - void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par); - void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par); - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par); - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par); - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par); - void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par); - void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par); - }; // End of class ConfigRsuSimulatorPort - -} // namespace ItsRSUsSimulator__TestSystem +#pragma once + +#include "ItsRSUsSimulator_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace ItsRSUsSimulator__TestSystem { + + class ConfigRsuSimulatorPort : public ConfigRsuSimulatorPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + ConfigRsuSimulatorPort(const char *par_port_name); + ~ConfigRsuSimulatorPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + void receiveMsg(const BOOLEAN &p_ind, const params &p_params); + void receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsCam__TypesAndValues::UtCamInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsCam__TypesAndValues::UtCamTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &p_ind, const params &p_params); + void receiveMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &p_ind, const params &p_params); + void receiveMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &p_ind, const params &p_params); + void receiveMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &p_ind, const params &p_params); + void receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &p_ind, const params &p_params); + void receiveMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &p_ind, const params &p_params); + void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &p_ind, const params &p_params); + void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &p_ind, const params &p_params); + void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &p_ind, const params &p_params); + void receiveMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &p_ind, const params &p_params); + + /*void send(const CfInitialize& send_par, const COMPONENT& destination_component); + void send(const CfInitialize& send_par); + void send(const CfInitialize_template& send_par, const COMPONENT& destination_component); + void send(const CfInitialize_template& send_par); + void send(const BOOLEAN& send_par, const COMPONENT& destination_component); + void send(const BOOLEAN& send_par); + void send(const BOOLEAN_template& send_par, const COMPONENT& destination_component); + void send(const BOOLEAN_template& send_par); + void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults& send_par, const COMPONENT& destination_component); + void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults& send_par); + void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults_template& send_par, const COMPONENT& destination_component); + void send(const LibItsGeoNetworking__TypesAndValues::UtGnResults_template& send_par);*/ + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const CfInitialize &send_par); + void outgoing_send(const BOOLEAN &send_par); + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnResults &send_par); + void outgoing_send(const LibItsGeoNetworking__TypesAndValues::UtGnEventInd &send_par); + void outgoing_send(const LibItsCam__TypesAndValues::UtCamResults &send_par); + void outgoing_send(const LibItsCam__TypesAndValues::UtCamEventInd &send_par); + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmResults &send_par); + void outgoing_send(const LibItsDenm__TypesAndValues::UtDenmEventInd &send_par); + void outgoing_send(const LibItsPki__TypesAndValues::UtPkiResults &send_par); + void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimResults &send_par); + void outgoing_send(const LibItsIvim__TypesAndValues::UtIvimEventInd &send_par); + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &send_par); + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &send_par); + void outgoing_send(const LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &send_par); + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremResults &send_par); + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremEventInd &send_par); + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSsemEventInd &send_par); + void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemResults &send_par); + void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &send_par); + }; // End of class ConfigRsuSimulatorPort + +} // namespace ItsRSUsSimulator__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/module.mk b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/module.mk index 2361270f17b9f261a9e2b7e2b559f8b67a99a814..3a2b355d27dad706c08d2ff266d09182f0559fff 100644 --- a/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/RSUsSimulator_ports/module.mk @@ -1,3 +1,3 @@ -sources := ConfigRsuSimulatorCodec.cc ConfigRsuSimulatorLayer.cc ConfigRsuSimulatorPort.cc -includes := . - +sources := ConfigRsuSimulatorCodec.cc ConfigRsuSimulatorLayer.cc ConfigRsuSimulatorPort.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.cc b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.cc index ae87564f01213e9514d97e9aa39d235b42f8d812..b7014008708c89a8349dd6439fa772317b3c24bf 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.cc +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.cc @@ -1,66 +1,66 @@ -#include "loggers.hh" -#include "registration.hh" - -#include "RtcmemLayer.hh" - -#include "AdapterControlPort_Rtcmem.hh" -//============================================================================= -namespace LibItsRtcmem__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - RtcmemLayer *p = registration::get_instance().get_item(std::string("RTCMEM")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: RTCMEM not registered"); - } - } - -} // namespace LibItsRtcmem__TestSystem +#include "loggers.hh" +#include "registration.hh" + +#include "RtcmemLayer.hh" + +#include "AdapterControlPort_Rtcmem.hh" +//============================================================================= +namespace LibItsRtcmem__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + RtcmemLayer *p = registration::get_instance().get_item(std::string("RTCMEM")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: RTCMEM not registered"); + } + } + +} // namespace LibItsRtcmem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.hh b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.hh index 93352555a2ad7d2c16a70511a29831d1708ea24c..5c8bb1156cf564abdaba0c1a3c2d7a01a6227822 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.hh +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/AdapterControlPort_Rtcmem.hh @@ -1,35 +1,35 @@ -#ifndef AdapterControlPort_Rtcmem_HH -#define AdapterControlPort_Rtcmem_HH - -//============================================================================= -#include "LibItsRtcmem_TestSystem.hh" - -namespace LibItsRtcmem__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsRtcmem__TestSystem - -#endif +#ifndef AdapterControlPort_Rtcmem_HH +#define AdapterControlPort_Rtcmem_HH + +//============================================================================= +#include "LibItsRtcmem_TestSystem.hh" + +namespace LibItsRtcmem__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsRtcmem__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.cc b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.cc index a821d118e2a5174d30772f25cab1faa9d6c539d4..377289dafa9ed69500619f98cd4f94ad682fdd2d 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.cc +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.cc @@ -66,7 +66,7 @@ namespace LibItsRtcmem__TestSystem { void RtcmemPort::user_stop() {} - void RtcmemPort::outgoing_send(const RtcmemReq &send_par) { + void RtcmemPort::outgoing_send(const LibItsRtcmem__TypesAndValues::RtcmemReq &send_par) { loggers::get_instance().log_msg(">>> RtcmemPort::outgoing_send: payload=", send_par); float duration; @@ -76,7 +76,7 @@ namespace LibItsRtcmem__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void RtcmemPort::receiveMsg(const LibItsRtcmem__TestSystem::RtcmemInd &p_ind, const params &p_params) { + void RtcmemPort::receiveMsg(const LibItsRtcmem__TypesAndValues::RtcmemInd &p_ind, const params &p_params) { loggers::get_instance().log_msg(">>> RtcmemPort::receive_msg: ", p_ind); incoming_message(p_ind); diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.hh b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.hh index 2766dbce86ee6eda6ee86aa586f35f6ae5e93f9a..d3078b4c32b1e905f42536ba0de807f2e87cafc6 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.hh +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/RtcmemPort.hh @@ -26,7 +26,7 @@ namespace LibItsRtcmem__TestSystem { void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const LibItsRtcmem__TestSystem::RtcmemInd &, const params &); + void receiveMsg(const LibItsRtcmem__TypesAndValues::RtcmemInd &, const params &); private: /* void Handle_Fd_Event(int fd, boolean is_readable, @@ -42,7 +42,7 @@ namespace LibItsRtcmem__TestSystem { void user_start(); void user_stop(); - void outgoing_send(const RtcmemReq &send_par); + void outgoing_send(const LibItsRtcmem__TypesAndValues::RtcmemReq &send_par); }; } // namespace LibItsRtcmem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.cc b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.cc index ae0a041244fda1b683d49fc6568725e167132f70..5ff19f882c5555487ec076a718f40a4024cd54c6 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.cc +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.cc @@ -1,115 +1,115 @@ -#include "UpperTesterRtcmemFactory.hh" - -#include "UpperTesterPort_Rtcmem.hh" -#include "loggers.hh" -//============================================================================= -namespace LibItsRtcmem__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Rtcmem::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_Rtcmem::UpperTesterPort_Rtcmem"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_Rtcmem::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Rtcmem::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_Rtcmem::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_Rtcmem::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_Rtcmem::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_Rtcmem::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_Rtcmem::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - loggers::get_instance().log("UpperTesterPort_Rtcmem::receive_msg: %s", p_ind.get_descriptor()->name); - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemResults") == 0) { // TODO To be refined - incoming_message((LibItsRtcmem__TypesAndValues::UtRtcmemResults &)p_ind); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } - } - -} // namespace LibItsRtcmem__TestSystem +#include "UpperTesterRtcmemFactory.hh" + +#include "UpperTesterPort_Rtcmem.hh" +#include "loggers.hh" +//============================================================================= +namespace LibItsRtcmem__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_Rtcmem::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_Rtcmem::UpperTesterPort_Rtcmem"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_Rtcmem::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Rtcmem::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_Rtcmem::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_Rtcmem::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_Rtcmem::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_Rtcmem::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_Rtcmem::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + loggers::get_instance().log("UpperTesterPort_Rtcmem::receive_msg: %s", p_ind.get_descriptor()->name); + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemResults") == 0) { // TODO To be refined + incoming_message((LibItsRtcmem__TypesAndValues::UtRtcmemResults &)p_ind); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } + } + +} // namespace LibItsRtcmem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.hh b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.hh index 730d68474c787954f278aba701b875da5bf71e30..7db3b7cdf9fb1a4c6666bcc4a076aedda4532fa4 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.hh +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/UpperTesterPort_Rtcmem.hh @@ -1,50 +1,50 @@ -#ifndef UpperTesterPort_Rtcmem_HH -#define UpperTesterPort_Rtcmem_HH - -#include "layer.hh" -#include "params.hh" - -//============================================================================= -#include "LibItsRtcmem_TestSystem.hh" -namespace LibItsRtcmem__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par); - - void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par); - - void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par); - - void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par); - }; - -} // namespace LibItsRtcmem__TestSystem - -#endif +#ifndef UpperTesterPort_Rtcmem_HH +#define UpperTesterPort_Rtcmem_HH + +#include "layer.hh" +#include "params.hh" + +//============================================================================= +#include "LibItsRtcmem_TestSystem.hh" +namespace LibItsRtcmem__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par); + + void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par); + + void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par); + + void outgoing_send(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par); + }; + +} // namespace LibItsRtcmem__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/module.mk b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/module.mk index 238ffc662dc93371318171261903fa7d4902d15e..79e92f530bf392b3d4a1d0a2e9ace2cc983cf721 100644 --- a/ccsrc/Ports/LibIts_ports/Rtcmem_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/Rtcmem_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_Rtcmem.cc RtcmemPort.cc UpperTesterPort_Rtcmem.cc -includes := . - +sources := AdapterControlPort_Rtcmem.cc RtcmemPort.cc UpperTesterPort_Rtcmem.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.cc b/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.cc index a585c3719c67affb3fb0f354ed108bb30483e0b0..95d1bba1606dc79b34c158d4c3e11a60b7b8e913 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.cc +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.cc @@ -1,66 +1,66 @@ -#include "loggers.hh" -#include "registration.hh" - -#include "SremSsemLayer.hh" - -//============================================================================= -#include "AdapterControlPort_SremSsem.hh" -namespace LibItsSremSsem__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { - loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); - - // Register this object for AdapterControlPort - SremSsemLayer *p = registration::get_instance().get_item(std::string("SremSsem")); - if (p != NULL) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); - LibItsCommon__TypesAndValues::AdapterControlResults response; - response.acSecResponse() = BOOLEAN(true); - if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); - std::string str(static_cast(send_par.acEnableSecurity().certificateId())); - if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { - loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); - if (p->disable_secured_mode() == -1) { - response.acSecResponse() = BOOLEAN(false); - } - } else { - response.acSecResponse() = BOOLEAN(false); - } - // Send response - loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); - incoming_message(response); - } else { - loggers::get_instance().error("AdapterControlPort::outgoing_send: SremSsem not registered"); - } - } - -} // namespace LibItsSremSsem__TestSystem +#include "loggers.hh" +#include "registration.hh" + +#include "SremSsemLayer.hh" + +//============================================================================= +#include "AdapterControlPort_SremSsem.hh" +namespace LibItsSremSsem__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par) { + loggers::get_instance().log_msg(">>> AdapterControlPort::outgoing_send: ", send_par); + + // Register this object for AdapterControlPort + SremSsemLayer *p = registration::get_instance().get_item(std::string("SremSsem")); + if (p != NULL) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Got GN layer %p", p); + LibItsCommon__TypesAndValues::AdapterControlResults response; + response.acSecResponse() = BOOLEAN(true); + if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acEnableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Enable secured mode"); + std::string str(static_cast(send_par.acEnableSecurity().certificateId())); + if (p->enable_secured_mode(str, send_par.acEnableSecurity().enforceSecurity()) == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else if (send_par.ischosen(LibItsCommon__TypesAndValues::AcSecPrimitive::ALT_acDisableSecurity)) { + loggers::get_instance().log("AdapterControlPort::outgoing_send: Disable secured mode"); + if (p->disable_secured_mode() == -1) { + response.acSecResponse() = BOOLEAN(false); + } + } else { + response.acSecResponse() = BOOLEAN(false); + } + // Send response + loggers::get_instance().log_msg("AdapterControlPort::outgoing_send: Send response: ", response); + incoming_message(response); + } else { + loggers::get_instance().error("AdapterControlPort::outgoing_send: SremSsem not registered"); + } + } + +} // namespace LibItsSremSsem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.hh b/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.hh index 0aa6035b22291a66d8342f744eaa4ffa90663e7b..e3b861ca77d384dd080c07dc40b48443eb06a6c2 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.hh +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/AdapterControlPort_SremSsem.hh @@ -1,34 +1,34 @@ -//============================================================================= -#ifndef AdapterControlPort_SremSsem_HH -#define AdapterControlPort_SremSsem_HH - -#include "LibItsSremSsem_TestSystem.hh" - -namespace LibItsSremSsem__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); - }; - -} // namespace LibItsSremSsem__TestSystem -#endif +//============================================================================= +#ifndef AdapterControlPort_SremSsem_HH +#define AdapterControlPort_SremSsem_HH + +#include "LibItsSremSsem_TestSystem.hh" + +namespace LibItsSremSsem__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsCommon__TypesAndValues::AcSecPrimitive &send_par); + }; + +} // namespace LibItsSremSsem__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.cc b/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.cc index 83248529a926e6b8c251a7664621cbcb03ec99b7..365debd48881f55b7b90fd68f36dc899f29f57ab 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.cc +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.cc @@ -66,7 +66,7 @@ namespace LibItsSremSsem__TestSystem { void SremSsemPort::user_stop() {} - void SremSsemPort::outgoing_send(const SremReq &send_par) { + void SremSsemPort::outgoing_send(const LibItsSremSsem__TypesAndValues::SremReq &send_par) { loggers::get_instance().log_msg(">>> SremSsemPort::outgoing_send: payload=", send_par); float duration; @@ -76,7 +76,7 @@ namespace LibItsSremSsem__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void SremSsemPort::outgoing_send(const SsemReq &send_par) { + void SremSsemPort::outgoing_send(const LibItsSremSsem__TypesAndValues::SsemReq &send_par) { loggers::get_instance().log_msg(">>> SremSsemPort::outgoing_send: payload=", send_par); float duration; @@ -86,13 +86,13 @@ namespace LibItsSremSsem__TestSystem { loggers::get_instance().set_stop_time(_time_key, duration); } - void SremSsemPort::receiveMsg(const LibItsSremSsem__TestSystem::SremInd &p_ind, const params &p_params) { + void SremSsemPort::receiveMsg(const LibItsSremSsem__TypesAndValues::SremInd &p_ind, const params &p_params) { loggers::get_instance().log_msg(">>> SremSsemPort::receive_msg: ", p_ind); incoming_message(p_ind); } - void SremSsemPort::receiveMsg(const LibItsSremSsem__TestSystem::SsemInd &p_ind, const params &p_params) { + void SremSsemPort::receiveMsg(const LibItsSremSsem__TypesAndValues::SsemInd &p_ind, const params &p_params) { loggers::get_instance().log_msg(">>> SremSsemPort::receive_msg: ", p_ind); incoming_message(p_ind); diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.hh b/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.hh index 5edd2c4442d3f6379717c1d61e21ab17f8cf803f..58ce110d3113bc1c83888c5f509f41c8ab1d2272 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.hh +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/SremSsemPort.hh @@ -26,9 +26,9 @@ namespace LibItsSremSsem__TestSystem { void set_parameter(const char *parameter_name, const char *parameter_value); - void receiveMsg(const LibItsSremSsem__TestSystem::SremInd &, const params &); + void receiveMsg(const LibItsSremSsem__TypesAndValues::SremInd &, const params &); - void receiveMsg(const LibItsSremSsem__TestSystem::SsemInd &, const params &); + void receiveMsg(const LibItsSremSsem__TypesAndValues::SsemInd &, const params &); private: /* void Handle_Fd_Event(int fd, boolean is_readable, @@ -44,9 +44,9 @@ namespace LibItsSremSsem__TestSystem { void user_start(); void user_stop(); - void outgoing_send(const SremReq &send_par); + void outgoing_send(const LibItsSremSsem__TypesAndValues::SremReq &send_par); - void outgoing_send(const SsemReq &send_par); + void outgoing_send(const LibItsSremSsem__TypesAndValues::SsemReq &send_par); }; } // namespace LibItsSremSsem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.cc b/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.cc index 93399fb7041eb35825cab65249a7e9df51af7e44..96e48e3a6c2d3a9c5f1904fc471358c801fa9bd7 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.cc +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.cc @@ -1,117 +1,117 @@ -#include "UpperTesterSremSsemFactory.hh" - -#include "UpperTesterPort_SremSsem.hh" -#include "loggers.hh" -//============================================================================= -namespace LibItsSremSsem__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) - : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_SremSsem::outgoing_send") { - loggers::get_instance().log("UpperTesterPort_SremSsem::UpperTesterPort_SremSsem"); - } - - UpperTesterPort::~UpperTesterPort() { - if (_layer != NULL) { - delete _layer; - } - } - - void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { - loggers::get_instance().log("UpperTesterPort_SremSsem::set_parameter: %s=%s", parameter_name, parameter_value); - _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); - _cfg_params.log(); - } - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_SremSsem::user_map: %s", system_port); - // Build layer stack - params::iterator it = _cfg_params.find(std::string("params")); - if (it != _cfg_params.end()) { - loggers::get_instance().log("UpperTesterPort_SremSsem::user_map: %s", it->second.c_str()); - _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); - if (static_cast(_layer) == NULL) { - loggers::get_instance().error("UpperTesterPort_SremSsem::user_map: Invalid stack configuration: %s", it->second.c_str()); - } - static_cast(_layer)->add_upper_port(this); - } else { - loggers::get_instance().error("UpperTesterPort_SremSsem::user_map: No layers defined in configuration file"); - } - } - - void UpperTesterPort::user_unmap(const char *system_port) { - loggers::get_instance().log(">>> UpperTesterPort_SremSsem::user_unmap: %s", system_port); - if (_layer != NULL) { - delete _layer; - _layer = NULL; - } - } - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par) { - loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); - - float duration; - loggers::get_instance().set_start_time(_time_key); - static_cast(_layer)->sendMsg(send_par, _layer_params); - loggers::get_instance().set_stop_time(_time_key, duration); - } - - void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterPort_SremSsem::receive_msg: ", p_ind); - // Sanity check - if (!p_ind.is_bound()) { - return; - } - - loggers::get_instance().log("UpperTesterPort_SremSsem::receive_msg: %s", p_ind.get_descriptor()->name); - if (std::string(p_ind.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremResults") == 0) { // TODO To be refined - incoming_message((LibItsSremSsem__TypesAndValues::UtSremResults &)p_ind); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSsemEventInd") == 0) { - incoming_message(static_cast(p_ind)); - } - } - -} // namespace LibItsSremSsem__TestSystem +#include "UpperTesterSremSsemFactory.hh" + +#include "UpperTesterPort_SremSsem.hh" +#include "loggers.hh" +//============================================================================= +namespace LibItsSremSsem__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) + : UpperTesterPort_BASE(par_port_name), _cfg_params(), _layer_params(), _layer(NULL), _time_key("UpperTesterPort_SremSsem::outgoing_send") { + loggers::get_instance().log("UpperTesterPort_SremSsem::UpperTesterPort_SremSsem"); + } + + UpperTesterPort::~UpperTesterPort() { + if (_layer != NULL) { + delete _layer; + } + } + + void UpperTesterPort::set_parameter(const char *parameter_name, const char *parameter_value) { + loggers::get_instance().log("UpperTesterPort_SremSsem::set_parameter: %s=%s", parameter_name, parameter_value); + _cfg_params.insert(std::pair(std::string(parameter_name), std::string(parameter_value))); + _cfg_params.log(); + } + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_SremSsem::user_map: %s", system_port); + // Build layer stack + params::iterator it = _cfg_params.find(std::string("params")); + if (it != _cfg_params.end()) { + loggers::get_instance().log("UpperTesterPort_SremSsem::user_map: %s", it->second.c_str()); + _layer = layer_stack_builder::get_instance()->create_layer_stack(it->second.c_str()); + if (static_cast(_layer) == NULL) { + loggers::get_instance().error("UpperTesterPort_SremSsem::user_map: Invalid stack configuration: %s", it->second.c_str()); + } + static_cast(_layer)->add_upper_port(this); + } else { + loggers::get_instance().error("UpperTesterPort_SremSsem::user_map: No layers defined in configuration file"); + } + } + + void UpperTesterPort::user_unmap(const char *system_port) { + loggers::get_instance().log(">>> UpperTesterPort_SremSsem::user_unmap: %s", system_port); + if (_layer != NULL) { + delete _layer; + _layer = NULL; + } + } + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par) { + loggers::get_instance().log_msg(">>> UppertesterPort::outgoing_send: ", send_par); + + float duration; + loggers::get_instance().set_start_time(_time_key); + static_cast(_layer)->sendMsg(send_par, _layer_params); + loggers::get_instance().set_stop_time(_time_key, duration); + } + + void UpperTesterPort::receiveMsg(const Base_Type &p_ind, const params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterPort_SremSsem::receive_msg: ", p_ind); + // Sanity check + if (!p_ind.is_bound()) { + return; + } + + loggers::get_instance().log("UpperTesterPort_SremSsem::receive_msg: %s", p_ind.get_descriptor()->name); + if (std::string(p_ind.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremResults") == 0) { // TODO To be refined + incoming_message((LibItsSremSsem__TypesAndValues::UtSremResults &)p_ind); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } else if (std::string(p_ind.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSsemEventInd") == 0) { + incoming_message(static_cast(p_ind)); + } + } + +} // namespace LibItsSremSsem__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.hh b/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.hh index fc1adbe7ed8857510fd4bbf0daa7f107e13df044..8a550437d16d180cfec4ca53ad1b80ee0fae788a 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.hh +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/UpperTesterPort_SremSsem.hh @@ -1,50 +1,50 @@ -//============================================================================= -#ifndef UpperTesterPort_SremSsem_HH -#define UpperTesterPort_SremSsem_HH - -#include "LibItsSremSsem_TestSystem.hh" - -#include "layer.hh" -#include "params.hh" - -namespace LibItsSremSsem__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - params _cfg_params; - params _layer_params; - layer * _layer; - std::string _time_key; - - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - void receiveMsg(const Base_Type &, const params &); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par); - - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par); - - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par); - - void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par); - }; - -} // namespace LibItsSremSsem__TestSystem -#endif +//============================================================================= +#ifndef UpperTesterPort_SremSsem_HH +#define UpperTesterPort_SremSsem_HH + +#include "LibItsSremSsem_TestSystem.hh" + +#include "layer.hh" +#include "params.hh" + +namespace LibItsSremSsem__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + params _cfg_params; + params _layer_params; + layer * _layer; + std::string _time_key; + + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + void receiveMsg(const Base_Type &, const params &); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par); + + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par); + + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par); + + void outgoing_send(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par); + }; + +} // namespace LibItsSremSsem__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/SremSsem_ports/module.mk b/ccsrc/Ports/LibIts_ports/SremSsem_ports/module.mk index b337391b512d962f316e4a729b38f5e0162e08b6..b344cdb1b14cb390db43949f9522c56277bcdf70 100644 --- a/ccsrc/Ports/LibIts_ports/SremSsem_ports/module.mk +++ b/ccsrc/Ports/LibIts_ports/SremSsem_ports/module.mk @@ -1,3 +1,3 @@ -sources := AdapterControlPort_SremSsem.cc SremSsemPort.cc UpperTesterPort_SremSsem.cc -includes := . - +sources := AdapterControlPort_SremSsem.cc SremSsemPort.cc UpperTesterPort_SremSsem.cc +includes := . + diff --git a/ccsrc/Ports/LibIts_ports/UpperTesterPort.hh b/ccsrc/Ports/LibIts_ports/UpperTesterPort.hh index f03230e88e40cc13e3907ccf6453c8fb4f8cdaaa..b0706e13d0839ace9be86457607fb8d1ea64418f 100644 --- a/ccsrc/Ports/LibIts_ports/UpperTesterPort.hh +++ b/ccsrc/Ports/LibIts_ports/UpperTesterPort.hh @@ -26,7 +26,7 @@ #endif #ifdef AtsSecurity -#include "BTP_ports/UpperTesterPort_BTP.hh" +//#include "BTP_ports/UpperTesterPort_BTP.hh" #include "CAM_ports/UpperTesterPort_CAM.hh" #include "DENM_ports/UpperTesterPort_DENM.hh" #include "GN_ports/UpperTesterPort_GN.hh" @@ -50,8 +50,12 @@ #include "SremSsem_ports/UpperTesterPort_SremSsem.hh" #endif +#ifdef AtsIPv6OverGeoNetworking +#include "GN_ports/UpperTesterPort_GN.hh" +#endif + #ifdef AtsRSUsSimulator // This is not an Abstract Test Suit, but an helper tool to simulate basic RSU/OBU functionalities -#include "BTP_ports/UpperTesterPort_BTP.hh" +//#include "BTP_ports/UpperTesterPort_BTP.hh" #include "CAM_ports/UpperTesterPort_CAM.hh" #include "DENM_ports/UpperTesterPort_DENM.hh" #include "GN_ports/UpperTesterPort_GN.hh" @@ -85,14 +89,14 @@ #endif #ifdef AtsSecurity -#include "UpperTesterPort_BTP.hh" +//#include "UpperTesterPort_BTP.hh" #include "UpperTesterPort_CAM.hh" #include "UpperTesterPort_DENM.hh" #include "UpperTesterPort_GN.hh" #endif #ifdef AtsPki -#include "UpperTesterPort_BTP.hh" +//#include "UpperTesterPort_BTP.hh" #include "UpperTesterPort_CAM.hh" #include "UpperTesterPort_DENM.hh" #include "UpperTesterPort_GN.hh" @@ -102,6 +106,13 @@ //#include "UpperTesterPort_BTP.hh" #include "UpperTesterPort_GN.hh" #include "UpperTesterPort_IVIM.hh" +#include "UpperTesterPort_MapemSpatem.hh" +#include "UpperTesterPort_Rtcmem.hh" +#include "UpperTesterPort_SremSsem.hh" +#endif + +#ifdef AtsIPv6OverGeoNetworking +#include "UpperTesterPort_GN.hh" #endif #ifdef AtsRSUsSimulator // This is not an Abstract Test Suit, but an helper tool to simulate basic RSU/OBU functionalities diff --git a/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.cc b/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.cc index 8640cf30a234c595edc3a1086d74c1be766fd8da..c2f59e9a25d27809e89fc9d9e9e464d179d100db 100644 --- a/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.cc +++ b/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.cc @@ -1,32 +1,32 @@ -//============================================================================= -#include "AdapterControlPort_V2G.hh" -namespace LibItsV2G__TestSystem { - - AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} - - AdapterControlPort::~AdapterControlPort() {} - - void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ - - void AdapterControlPort::user_map(const char * /*system_port*/) {} - - void AdapterControlPort::user_unmap(const char * /*system_port*/) {} - - void AdapterControlPort::user_start() {} - - void AdapterControlPort::user_stop() {} - - void AdapterControlPort::outgoing_send(const LibItsV2G__TypesAndValues::AcV2Gprimitive & /*send_par*/) {} - -} // namespace LibItsV2G__TestSystem +//============================================================================= +#include "AdapterControlPort_V2G.hh" +namespace LibItsV2G__TestSystem { + + AdapterControlPort::AdapterControlPort(const char *par_port_name) : AdapterControlPort_BASE(par_port_name) {} + + AdapterControlPort::~AdapterControlPort() {} + + void AdapterControlPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void AdapterControlPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void AdapterControlPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void AdapterControlPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void AdapterControlPort::Handle_Timeout(double time_since_last_call) {}*/ + + void AdapterControlPort::user_map(const char * /*system_port*/) {} + + void AdapterControlPort::user_unmap(const char * /*system_port*/) {} + + void AdapterControlPort::user_start() {} + + void AdapterControlPort::user_stop() {} + + void AdapterControlPort::outgoing_send(const LibItsV2G__TypesAndValues::AcV2Gprimitive & /*send_par*/) {} + +} // namespace LibItsV2G__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.hh b/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.hh index f6b281ad2f5b6ca0377ba9f396115a991f38fd2e..800943b7734b31a1ca8bb880cd270bc5ffcc12d6 100644 --- a/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.hh +++ b/ccsrc/Ports/LibIts_ports/V2G_ports/AdapterControlPort_V2G.hh @@ -1,33 +1,33 @@ -//============================================================================= -#ifndef AdapterControlPort_V2G_HH -#define AdapterControlPort_V2G_HH - -#include "LibItsV2G_TestSystem.hh" -namespace LibItsV2G__TestSystem { - - class AdapterControlPort : public AdapterControlPort_BASE { - public: - AdapterControlPort(const char *par_port_name = NULL); - ~AdapterControlPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsV2G__TypesAndValues::AcV2Gprimitive &send_par); - }; - -} // namespace LibItsV2G__TestSystem -#endif +//============================================================================= +#ifndef AdapterControlPort_V2G_HH +#define AdapterControlPort_V2G_HH + +#include "LibItsV2G_TestSystem.hh" +namespace LibItsV2G__TestSystem { + + class AdapterControlPort : public AdapterControlPort_BASE { + public: + AdapterControlPort(const char *par_port_name = NULL); + ~AdapterControlPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsV2G__TypesAndValues::AcV2Gprimitive &send_par); + }; + +} // namespace LibItsV2G__TestSystem +#endif diff --git a/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.cc b/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.cc index c2a58cfeb1b220c041f80b239aef472ecc8930f8..056f76694ffee0d4425e58e96b1fd4fc2d598a7e 100644 --- a/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.cc +++ b/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.cc @@ -1,36 +1,36 @@ -//============================================================================= -#include "UpperTesterPort_V2G.hh" -namespace LibItsV2G__TestSystem { - - UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} - - UpperTesterPort::~UpperTesterPort() {} - - void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} - - void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ - - void UpperTesterPort::user_map(const char * /*system_port*/) {} - - void UpperTesterPort::user_unmap(const char * /*system_port*/) {} - - void UpperTesterPort::user_start() {} - - void UpperTesterPort::user_stop() {} - - void UpperTesterPort::outgoing_send(const LibItsV2G__TypesAndValues::UtInitialize & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsV2G__TypesAndValues::UtTrigger & /*send_par*/) {} - - void UpperTesterPort::outgoing_send(const LibItsV2G__TypesAndValues::UtCheck & /*send_par*/) {} - -} // namespace LibItsV2G__TestSystem +//============================================================================= +#include "UpperTesterPort_V2G.hh" +namespace LibItsV2G__TestSystem { + + UpperTesterPort::UpperTesterPort(const char *par_port_name) : UpperTesterPort_BASE(par_port_name) {} + + UpperTesterPort::~UpperTesterPort() {} + + void UpperTesterPort::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void UpperTesterPort::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void UpperTesterPort::Handle_Fd_Event_Error(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Writable(int /*fd*/) {} + + void UpperTesterPort::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void UpperTesterPort::Handle_Timeout(double time_since_last_call) {}*/ + + void UpperTesterPort::user_map(const char * /*system_port*/) {} + + void UpperTesterPort::user_unmap(const char * /*system_port*/) {} + + void UpperTesterPort::user_start() {} + + void UpperTesterPort::user_stop() {} + + void UpperTesterPort::outgoing_send(const LibItsV2G__TypesAndValues::UtInitialize & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsV2G__TypesAndValues::UtTrigger & /*send_par*/) {} + + void UpperTesterPort::outgoing_send(const LibItsV2G__TypesAndValues::UtCheck & /*send_par*/) {} + +} // namespace LibItsV2G__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.hh b/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.hh index 928bbe1be6331992ce4862ffec29169409239584..53d62d42c4a88d20cc09ba855361886e1baee5ba 100644 --- a/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.hh +++ b/ccsrc/Ports/LibIts_ports/V2G_ports/UpperTesterPort_V2G.hh @@ -1,38 +1,38 @@ -//============================================================================= -#ifndef UpperTesterPort_V2G_HH -#define UpperTesterPort_V2G_HH - -#include "LibItsV2G_TestSystem.hh" -namespace LibItsV2G__TestSystem { - - class UpperTesterPort : public UpperTesterPort_BASE { - public: - UpperTesterPort(const char *par_port_name = NULL); - ~UpperTesterPort(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const LibItsV2G__TypesAndValues::UtInitialize &send_par); - - void outgoing_send(const LibItsV2G__TypesAndValues::UtTrigger &send_par); - - void outgoing_send(const LibItsV2G__TypesAndValues::UtCheck &send_par); - }; - -} // namespace LibItsV2G__TestSystem - -#endif +//============================================================================= +#ifndef UpperTesterPort_V2G_HH +#define UpperTesterPort_V2G_HH + +#include "LibItsV2G_TestSystem.hh" +namespace LibItsV2G__TestSystem { + + class UpperTesterPort : public UpperTesterPort_BASE { + public: + UpperTesterPort(const char *par_port_name = NULL); + ~UpperTesterPort(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const LibItsV2G__TypesAndValues::UtInitialize &send_par); + + void outgoing_send(const LibItsV2G__TypesAndValues::UtTrigger &send_par); + + void outgoing_send(const LibItsV2G__TypesAndValues::UtCheck &send_par); + }; + +} // namespace LibItsV2G__TestSystem + +#endif diff --git a/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.cc b/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.cc index 59fe6b38e5e683ef91de092543f075564208fd95..e95403c36e28d0acfca4c3ceb1a65e2a7ae8f6a6 100644 --- a/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.cc +++ b/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.cc @@ -1,41 +1,41 @@ -// This Test Port skeleton source file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 13:23:50 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Complete the body of empty functions and -// add your member functions here. - -#include "V2Gport.hh" - -namespace LibItsV2G__TestSystem { - - V2Gport::V2Gport(const char *par_port_name) : V2Gport_BASE(par_port_name) {} - - V2Gport::~V2Gport() {} - - void V2Gport::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} - - /*void V2Gport::Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error) {}*/ - - void V2Gport::Handle_Fd_Event_Error(int /*fd*/) {} - - void V2Gport::Handle_Fd_Event_Writable(int /*fd*/) {} - - void V2Gport::Handle_Fd_Event_Readable(int /*fd*/) {} - - /*void V2Gport::Handle_Timeout(double time_since_last_call) {}*/ - - void V2Gport::user_map(const char * /*system_port*/) {} - - void V2Gport::user_unmap(const char * /*system_port*/) {} - - void V2Gport::user_start() {} - - void V2Gport::user_stop() {} - - void V2Gport::outgoing_send(const V2Greq & /*send_par*/) {} - -} // namespace LibItsV2G__TestSystem +// This Test Port skeleton source file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 13:23:50 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Complete the body of empty functions and +// add your member functions here. + +#include "V2Gport.hh" + +namespace LibItsV2G__TestSystem { + + V2Gport::V2Gport(const char *par_port_name) : V2Gport_BASE(par_port_name) {} + + V2Gport::~V2Gport() {} + + void V2Gport::set_parameter(const char * /*parameter_name*/, const char * /*parameter_value*/) {} + + /*void V2Gport::Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error) {}*/ + + void V2Gport::Handle_Fd_Event_Error(int /*fd*/) {} + + void V2Gport::Handle_Fd_Event_Writable(int /*fd*/) {} + + void V2Gport::Handle_Fd_Event_Readable(int /*fd*/) {} + + /*void V2Gport::Handle_Timeout(double time_since_last_call) {}*/ + + void V2Gport::user_map(const char * /*system_port*/) {} + + void V2Gport::user_unmap(const char * /*system_port*/) {} + + void V2Gport::user_start() {} + + void V2Gport::user_stop() {} + + void V2Gport::outgoing_send(const V2Greq & /*send_par*/) {} + +} // namespace LibItsV2G__TestSystem diff --git a/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.hh b/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.hh index b6ec18a4623d9bef85111b990465d83d9ac49876..4fc1d9c426fc5c1f19b0a8e20332996bcca72009 100644 --- a/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.hh +++ b/ccsrc/Ports/LibIts_ports/V2G_ports/V2Gport.hh @@ -1,43 +1,43 @@ -// This Test Port skeleton header file was generated by the -// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A -// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 13:23:50 2015 - -// Copyright Ericsson Telecom AB 2000-2014 - -// You may modify this file. Add your attributes and prototypes of your -// member functions here. - -#ifndef V2Gport_HH -#define V2Gport_HH - -#include "LibItsV2G_TestSystem.hh" - -namespace LibItsV2G__TestSystem { - - class V2Gport : public V2Gport_BASE { - public: - V2Gport(const char *par_port_name = NULL); - ~V2Gport(); - - void set_parameter(const char *parameter_name, const char *parameter_value); - - private: - /* void Handle_Fd_Event(int fd, boolean is_readable, - boolean is_writable, boolean is_error); */ - void Handle_Fd_Event_Error(int fd); - void Handle_Fd_Event_Writable(int fd); - void Handle_Fd_Event_Readable(int fd); - /* void Handle_Timeout(double time_since_last_call); */ - protected: - void user_map(const char *system_port); - void user_unmap(const char *system_port); - - void user_start(); - void user_stop(); - - void outgoing_send(const V2Greq &send_par); - }; - -} // namespace LibItsV2G__TestSystem - -#endif +// This Test Port skeleton header file was generated by the +// TTCN-3 Compiler of the TTCN-3 Test Executor version CRL 113 200/5 R3A +// for U-ERICSSON\ethgry (ethgry@HU00078339) on Sun Aug 16 13:23:50 2015 + +// Copyright Ericsson Telecom AB 2000-2014 + +// You may modify this file. Add your attributes and prototypes of your +// member functions here. + +#ifndef V2Gport_HH +#define V2Gport_HH + +#include "LibItsV2G_TestSystem.hh" + +namespace LibItsV2G__TestSystem { + + class V2Gport : public V2Gport_BASE { + public: + V2Gport(const char *par_port_name = NULL); + ~V2Gport(); + + void set_parameter(const char *parameter_name, const char *parameter_value); + + private: + /* void Handle_Fd_Event(int fd, boolean is_readable, + boolean is_writable, boolean is_error); */ + void Handle_Fd_Event_Error(int fd); + void Handle_Fd_Event_Writable(int fd); + void Handle_Fd_Event_Readable(int fd); + /* void Handle_Timeout(double time_since_last_call); */ + protected: + void user_map(const char *system_port); + void user_unmap(const char *system_port); + + void user_start(); + void user_stop(); + + void outgoing_send(const V2Greq &send_par); + }; + +} // namespace LibItsV2G__TestSystem + +#endif diff --git a/ccsrc/Protocols/BTP/btp_codec.cc b/ccsrc/Protocols/BTP/btp_codec.cc index c9ee8ea16937e7cd5766cc85b65fa3201374e865..47466449e09b9c8c745a1e919c05d38135f92ca4 100644 --- a/ccsrc/Protocols/BTP/btp_codec.cc +++ b/ccsrc/Protocols/BTP/btp_codec.cc @@ -1,136 +1,136 @@ -#include -//#include - -#include "btp_codec.hh" -#include "loggers.hh" - -#include "LibItsBtp_TypesAndValues.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -int btp_codec::encode(const LibItsBtp__TypesAndValues::BtpPacket &msg, OCTETSTRING &data) { - // loggers::get_instance().log_msg(">>> btp_codec::encode: ", (const Base_Type&)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - - // loggers::get_instance().log_msg("<<< btp_codec::encode: data=", data); - return 0; -} - -int btp_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - // loggers::get_instance().log(">>> btp_codec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); - // loggers::get_instance().log_msg(">>> btp_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - // loggers::get_instance().log("btp_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - // loggers::get_instance().log("btp_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - // r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - // loggers::get_instance().warning("btp_codec::encode_: -1 result code returned"); - return -1; - } - } - } // End of 'for' statement - } else if (std::string(field_descriptor.name).compare("@LibItsBtp_TypesAndValues.BtpPacket.payload") == 0) { - const OPTIONAL &v = dynamic_cast &>(type); - // loggers::get_instance().log("btp_codec::encode_: BtpRawPayload present: %d", v.is_present()); - if (v.is_present()) { - if (encode_(static_cast(*v.get_opt_value()), LibItsBtp__TypesAndValues::BtpRawPayload_descr_, - encoding_buffer) == -1) { - // loggers::get_instance().warning("btp_codec::encode_: -1 result code returned"); - return -1; - } - } - } else { - // loggers::get_instance().log("btp_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - - // loggers::get_instance().log_to_hexa("<<>> btp_codec::decode: decoding_buffer=", decoding_buffer); - decode_(msg, *msg.get_descriptor(), decoding_buffer); - - // loggers::get_instance().log_msg("<<< btp_codec::decode: ", (const Base_Type&)msg); - return 0; -} - -int btp_codec::decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer) { - // loggers::get_instance().log(">>> btp_codec::decode_: processing %s/%s (%d,%d,%p)", type.get_descriptor()->name, field_descriptor.name, - // decoding_buffer.get_len(), decoding_buffer.get_pos(), decoding_buffer.get_read_data()); - - if (dynamic_cast(&type) != NULL) { - Record_Type &r = (Record_Type &)type; - // loggers::get_instance().log("btp_codec::decode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - // loggers::get_instance().log("btp_codec::decode_: processing %s/%s/%s", r.fld_name(i), r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name); - if (decode_(*dynamic_cast(r.get_at(i)), *(r.fld_descr(i)), decoding_buffer) == -1) { - return -1; - } - } // End of 'for' statement - } else { - // loggers::get_instance().log("btp_codec::decode_ (else): processing type %s/%s - optional:%d", type.get_descriptor()->name, field_descriptor.name, - // type.is_optional()); - if (std::string(field_descriptor.name).compare("@LibItsBtp_TypesAndValues.BtpPacket.header") == 0) { - // loggers::get_instance().log("btp_codec::decode_: _type = %d", _type); - LibItsBtp__TypesAndValues::BtpHeader &b = static_cast(type); - if (_type == btp_codec::btpA) { - decode_(b.btpAHeader(), *b.btpAHeader().get_descriptor(), decoding_buffer); - if (_params != NULL) { - (*_params)[params::btp_type] = std::string("btpA"); - (*_params)[params::btp_destination_port] = std::to_string(static_cast(b.btpAHeader().destinationPort())); - } - } else if (_type == btp_codec::btpB) { - decode_(b.btpBHeader(), *b.btpBHeader().get_descriptor(), decoding_buffer); - if (_params != NULL) { - (*_params)[params::btp_type] = std::string("btpB"); - (*_params)[params::btp_destination_port] = std::to_string(static_cast(b.btpBHeader().destinationPort())); - (*_params)[params::btp_info] = std::to_string(static_cast(b.btpBHeader().destinationPortInfo())); - } - } else { - // loggers::get_instance().error("btp_codec::decode_: Invalid BTP type"); // Cannot be reached - } - // loggers::get_instance().log_msg("btp_codec::decode_: BtpHeader: ", type); - } else if (std::string(field_descriptor.name).compare("@LibItsBtp_TypesAndValues.BtpPacket.payload") == 0) { - if (decoding_buffer.get_len() == decoding_buffer.get_pos()) { // No payload, set it to omit - // loggers::get_instance().log("btp_codec::decode_: Set OPTIONAL to omit"); - dynamic_cast &>(type).set_to_omit(); - } else { - // Decode BtpRawPayload data structure - OCTETSTRING os(decoding_buffer.get_len() - decoding_buffer.get_pos(), decoding_buffer.get_data() + decoding_buffer.get_pos()); - // loggers::get_instance().log_msg("btp_codec::decode_: s=", os); - if (_params != NULL) { - (*_params)[params::btp_payload] = std::string(static_cast(oct2str(os))); - } - if (os.lengthof() != 0) { - dynamic_cast &>(type) = OPTIONAL(os); - // loggers::get_instance().log_msg("btp_codec::decode_: Set OPTIONAL to ", type); - } else { - // loggers::get_instance().log("btp_codec::decode_: Set OPTIONAL to omit"); - dynamic_cast &>(type).set_to_omit(); - } - } - } else { - type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); - } - } - - // loggers::get_instance().log_msg("<<< btp_codec::decode_: ", type); - // loggers::get_instance().log_to_hexa("<<< btp_codec::decode_: decoding_buffer=", decoding_buffer); - - return 0; -} +#include +//#include + +#include "btp_codec.hh" +#include "loggers.hh" + +#include "LibItsBtp_TypesAndValues.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +int btp_codec::encode(const LibItsBtp__TypesAndValues::BtpPacket &msg, OCTETSTRING &data) { + // loggers::get_instance().log_msg(">>> btp_codec::encode: ", (const Base_Type&)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + + // loggers::get_instance().log_msg("<<< btp_codec::encode: data=", data); + return 0; +} + +int btp_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + // loggers::get_instance().log(">>> btp_codec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); + // loggers::get_instance().log_msg(">>> btp_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + // loggers::get_instance().log("btp_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + // loggers::get_instance().log("btp_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + // r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + // loggers::get_instance().warning("btp_codec::encode_: -1 result code returned"); + return -1; + } + } + } // End of 'for' statement + } else if (std::string(field_descriptor.name).compare("@LibItsBtp_TypesAndValues.BtpPacket.payload") == 0) { + const OPTIONAL &v = dynamic_cast &>(type); + // loggers::get_instance().log("btp_codec::encode_: BtpRawPayload present: %d", v.is_present()); + if (v.is_present()) { + if (encode_(static_cast(*v.get_opt_value()), LibItsBtp__TypesAndValues::BtpRawPayload_descr_, + encoding_buffer) == -1) { + // loggers::get_instance().warning("btp_codec::encode_: -1 result code returned"); + return -1; + } + } + } else { + // loggers::get_instance().log("btp_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + + // loggers::get_instance().log_to_hexa("<<>> btp_codec::decode: decoding_buffer=", decoding_buffer); + decode_(msg, *msg.get_descriptor(), decoding_buffer); + + // loggers::get_instance().log_msg("<<< btp_codec::decode: ", (const Base_Type&)msg); + return 0; +} + +int btp_codec::decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer) { + // loggers::get_instance().log(">>> btp_codec::decode_: processing %s/%s (%d,%d,%p)", type.get_descriptor()->name, field_descriptor.name, + // decoding_buffer.get_len(), decoding_buffer.get_pos(), decoding_buffer.get_read_data()); + + if (dynamic_cast(&type) != NULL) { + Record_Type &r = (Record_Type &)type; + // loggers::get_instance().log("btp_codec::decode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + // loggers::get_instance().log("btp_codec::decode_: processing %s/%s/%s", r.fld_name(i), r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name); + if (decode_(*dynamic_cast(r.get_at(i)), *(r.fld_descr(i)), decoding_buffer) == -1) { + return -1; + } + } // End of 'for' statement + } else { + // loggers::get_instance().log("btp_codec::decode_ (else): processing type %s/%s - optional:%d", type.get_descriptor()->name, field_descriptor.name, + // type.is_optional()); + if (std::string(field_descriptor.name).compare("@LibItsBtp_TypesAndValues.BtpPacket.header") == 0) { + // loggers::get_instance().log("btp_codec::decode_: _type = %d", _type); + LibItsBtp__TypesAndValues::BtpHeader &b = static_cast(type); + if (_type == btp_codec::btpA) { + decode_(b.btpAHeader(), *b.btpAHeader().get_descriptor(), decoding_buffer); + if (_params != NULL) { + (*_params)[params::btp_type] = std::string("btpA"); + (*_params)[params::btp_destination_port] = std::to_string(static_cast(b.btpAHeader().destinationPort())); + } + } else if (_type == btp_codec::btpB) { + decode_(b.btpBHeader(), *b.btpBHeader().get_descriptor(), decoding_buffer); + if (_params != NULL) { + (*_params)[params::btp_type] = std::string("btpB"); + (*_params)[params::btp_destination_port] = std::to_string(static_cast(b.btpBHeader().destinationPort())); + (*_params)[params::btp_info] = std::to_string(static_cast(b.btpBHeader().destinationPortInfo())); + } + } else { + // loggers::get_instance().error("btp_codec::decode_: Invalid BTP type"); // Cannot be reached + } + // loggers::get_instance().log_msg("btp_codec::decode_: BtpHeader: ", type); + } else if (std::string(field_descriptor.name).compare("@LibItsBtp_TypesAndValues.BtpPacket.payload") == 0) { + if (decoding_buffer.get_len() == decoding_buffer.get_pos()) { // No payload, set it to omit + // loggers::get_instance().log("btp_codec::decode_: Set OPTIONAL to omit"); + dynamic_cast &>(type).set_to_omit(); + } else { + // Decode BtpRawPayload data structure + OCTETSTRING os(decoding_buffer.get_len() - decoding_buffer.get_pos(), decoding_buffer.get_data() + decoding_buffer.get_pos()); + // loggers::get_instance().log_msg("btp_codec::decode_: s=", os); + if (_params != NULL) { + (*_params)[params::btp_payload] = std::string(static_cast(oct2str(os))); + } + if (os.lengthof() != 0) { + dynamic_cast &>(type) = OPTIONAL(os); + // loggers::get_instance().log_msg("btp_codec::decode_: Set OPTIONAL to ", type); + } else { + // loggers::get_instance().log("btp_codec::decode_: Set OPTIONAL to omit"); + dynamic_cast &>(type).set_to_omit(); + } + } + } else { + type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); + } + } + + // loggers::get_instance().log_msg("<<< btp_codec::decode_: ", type); + // loggers::get_instance().log_to_hexa("<<< btp_codec::decode_: decoding_buffer=", decoding_buffer); + + return 0; +} diff --git a/ccsrc/Protocols/BTP/btp_codec.hh b/ccsrc/Protocols/BTP/btp_codec.hh index 296bcc16dc079a2b21be1ca13666610719fd89a2..e4570f66837aff69fd9ffd1bc88c2560933c22d6 100644 --- a/ccsrc/Protocols/BTP/btp_codec.hh +++ b/ccsrc/Protocols/BTP/btp_codec.hh @@ -1,39 +1,39 @@ -#ifndef BTPCODEC_H -#define BTPCODEC_H - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsBtp__TestSystem { - class BtpReq; - class BtpInd; -} // namespace LibItsBtp__TestSystem - -namespace LibItsBtp__TypesAndValues { - class BtpPacket; -} - -class btp_codec : public codec { - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - - int decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer); - -public: - enum BtpType { btpA, btpB }; - btp_codec() : codec() { _type = btp_codec::btpA; }; - virtual ~btp_codec(){}; - - virtual int encode(const LibItsBtp__TypesAndValues::BtpPacket &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, LibItsBtp__TypesAndValues::BtpPacket &, params *params = NULL); - - inline void set_btp_type(const btp_codec::BtpType p_btp_type) { _type = p_btp_type; }; - -private: - BtpType _type; -}; - -#endif +#ifndef BTPCODEC_H +#define BTPCODEC_H + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsBtp__TestSystem { + class BtpReq; + class BtpInd; +} // namespace LibItsBtp__TestSystem + +namespace LibItsBtp__TypesAndValues { + class BtpPacket; +} + +class btp_codec : public codec { + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + + int decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer); + +public: + enum BtpType { btpA, btpB }; + btp_codec() : codec() { _type = btp_codec::btpA; }; + virtual ~btp_codec(){}; + + virtual int encode(const LibItsBtp__TypesAndValues::BtpPacket &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, LibItsBtp__TypesAndValues::BtpPacket &, params *params = NULL); + + inline void set_btp_type(const btp_codec::BtpType p_btp_type) { _type = p_btp_type; }; + +private: + BtpType _type; +}; + +#endif diff --git a/ccsrc/Protocols/BTP/btp_layer.cc b/ccsrc/Protocols/BTP/btp_layer.cc index 54a30e1868c6682bc0f17ccbf8fc68d9b92f69a5..33d6376553337cb2952a7e1c7365fa024265b612 100644 --- a/ccsrc/Protocols/BTP/btp_layer.cc +++ b/ccsrc/Protocols/BTP/btp_layer.cc @@ -1,110 +1,110 @@ -#include "btp_types.hh" - -#include "btp_layer_factory.hh" - -#include "loggers.hh" - -#include "converter.hh" - -btp_layer::btp_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec(), _device_mode{true} { - loggers::get_instance().log(">>> btp_layer::btp_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - - // Sanity check - params::const_iterator it = _params.find(params::btp_type); - if (it == _params.cend()) { - _params[params::btp_type] = std::string("btpB"); - } - it = _params.find(params::btp_destination_port); - if (it == _params.cend()) { - _params[params::btp_destination_port] = std::to_string(2001); - } - it = _params.find(params::btp_info); - if (it == _params.cend()) { - _params[params::btp_info] = std::to_string(0); - } - it = _params.find(params::device_mode); - if (it != _params.cend()) { - _device_mode = (1 == converter::get_instance().string_to_int(it->second)); - } -} - -void btp_layer::sendMsg(const LibItsBtp__TestSystem::BtpReq &p, params ¶ms) { - loggers::get_instance().log(">>> btp_layer::sendMsg"); - // params.log(); - - // Encode BTP PDU - OCTETSTRING data; - _codec.encode(p.msgOut(), data); - send_data(data, params); -} - -void btp_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> btp_layer::send_data: ", data); - params.log(); // TODO To be removed - _params.log(); // TODO To be removed - - if (_device_mode) { - LibItsBtp__TypesAndValues::BtpHeader header; - std::string btp_type; - params::const_iterator it = params.find(params::next_header); - if (it != params.cend()) { - btp_type = it->second; - } else { - btp_type = _params[params::btp_type]; - } - loggers::get_instance().log("btp_layer::send_data: btp_type=%s", btp_type.c_str()); - int btp_destination_port = std::stoi(_params[params::btp_destination_port]); // Default value - it = params.find(params::btp_destination_port); - if (it != params.cend()) { - btp_destination_port = std::stoi(params[params::btp_destination_port]); // Overwritting default value - } - loggers::get_instance().log("btp_layer::send_data: btp_destination_port=%d", btp_destination_port); - if (btp_type.compare("btpA") == 0) { - header.btpAHeader() = LibItsBtp__TypesAndValues::BtpAHeader(btp_destination_port, std::stoi(_params[params::btp_info])); - } else { - header.btpBHeader() = LibItsBtp__TypesAndValues::BtpBHeader(btp_destination_port, std::stoi(_params[params::btp_info])); - } - LibItsBtp__TypesAndValues::BtpPacket p(header, data); - loggers::get_instance().log_msg("btp_layer::send_data: ", p); - - // Encode BTP PDU - OCTETSTRING os; - _codec.encode(p, os); - data = os; - } - - send_to_all_layers(data, params); -} - -void btp_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> btp_layer::receive_data: ", data); - params.log(); - // Decode the payload - LibItsBtp__TestSystem::BtpInd p; - loggers::get_instance().log("btp_layer::receive_data: Looking for %s", params::gn_next_header.c_str()); - params::const_iterator it = params.find(params::gn_next_header); - if (it != params.cend()) { - loggers::get_instance().log("btp_layer::receive_data: Call set_btp_type with %s/%d", it->second.c_str(), - (it->second.compare("2") == 0) ? btp_codec::btpB : btp_codec::btpA); - _codec.set_btp_type((it->second.compare("2") == 0) ? btp_codec::btpB : btp_codec::btpA); - } - _codec.decode(data, p.msgIn(), ¶ms); - - // Pass the BTP raw payload to the upper layers if any - it = params.find(params::btp_payload); - if (it != params.cend()) { - loggers::get_instance().log("btp_layer::receive_data: btp_payload=%s", it->second.c_str()); - OCTETSTRING os(str2oct(CHARSTRING(it->second.c_str()))); - receive_to_all_layers(os, params); - } else { - loggers::get_instance().warning("btp_layer::receive_data: No payload to pass to upper layers"); - } - // Pass it to the ports if any - // params.log(); - to_all_upper_ports(p, params); -} - -btp_layer_factory btp_layer_factory::_f; +#include "btp_types.hh" + +#include "btp_layer_factory.hh" + +#include "loggers.hh" + +#include "converter.hh" + +btp_layer::btp_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec(), _device_mode{true} { + loggers::get_instance().log(">>> btp_layer::btp_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + + // Sanity check + params::const_iterator it = _params.find(params::btp_type); + if (it == _params.cend()) { + _params[params::btp_type] = std::string("btpB"); + } + it = _params.find(params::btp_destination_port); + if (it == _params.cend()) { + _params[params::btp_destination_port] = std::to_string(2001); + } + it = _params.find(params::btp_info); + if (it == _params.cend()) { + _params[params::btp_info] = std::to_string(0); + } + it = _params.find(params::device_mode); + if (it != _params.cend()) { + _device_mode = (1 == converter::get_instance().string_to_int(it->second)); + } +} + +void btp_layer::sendMsg(const LibItsBtp__TypesAndValues::BtpReq &p, params ¶ms) { + loggers::get_instance().log(">>> btp_layer::sendMsg"); + // params.log(); + + // Encode BTP PDU + OCTETSTRING data; + _codec.encode(p.msgOut(), data); + send_data(data, params); +} + +void btp_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> btp_layer::send_data: ", data); + params.log(); // TODO To be removed + _params.log(); // TODO To be removed + + if (_device_mode) { + LibItsBtp__TypesAndValues::BtpHeader header; + std::string btp_type; + params::const_iterator it = params.find(params::next_header); + if (it != params.cend()) { + btp_type = it->second; + } else { + btp_type = _params[params::btp_type]; + } + loggers::get_instance().log("btp_layer::send_data: btp_type=%s", btp_type.c_str()); + int btp_destination_port = std::stoi(_params[params::btp_destination_port]); // Default value + it = params.find(params::btp_destination_port); + if (it != params.cend()) { + btp_destination_port = std::stoi(params[params::btp_destination_port]); // Overwritting default value + } + loggers::get_instance().log("btp_layer::send_data: btp_destination_port=%d", btp_destination_port); + if (btp_type.compare("btpA") == 0) { + header.btpAHeader() = LibItsBtp__TypesAndValues::BtpAHeader(btp_destination_port, std::stoi(_params[params::btp_info])); + } else { + header.btpBHeader() = LibItsBtp__TypesAndValues::BtpBHeader(btp_destination_port, std::stoi(_params[params::btp_info])); + } + LibItsBtp__TypesAndValues::BtpPacket p(header, data); + loggers::get_instance().log_msg("btp_layer::send_data: ", p); + + // Encode BTP PDU + OCTETSTRING os; + _codec.encode(p, os); + data = os; + } + + send_to_all_layers(data, params); +} + +void btp_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> btp_layer::receive_data: ", data); + params.log(); + // Decode the payload + LibItsBtp__TypesAndValues::BtpInd p; + loggers::get_instance().log("btp_layer::receive_data: Looking for %s", params::gn_next_header.c_str()); + params::const_iterator it = params.find(params::gn_next_header); + if (it != params.cend()) { + loggers::get_instance().log("btp_layer::receive_data: Call set_btp_type with %s/%d", it->second.c_str(), + (it->second.compare("2") == 0) ? btp_codec::btpB : btp_codec::btpA); + _codec.set_btp_type((it->second.compare("2") == 0) ? btp_codec::btpB : btp_codec::btpA); + } + _codec.decode(data, p.msgIn(), ¶ms); + + // Pass the BTP raw payload to the upper layers if any + it = params.find(params::btp_payload); + if (it != params.cend()) { + loggers::get_instance().log("btp_layer::receive_data: btp_payload=%s", it->second.c_str()); + OCTETSTRING os(str2oct(CHARSTRING(it->second.c_str()))); + receive_to_all_layers(os, params); + } else { + loggers::get_instance().warning("btp_layer::receive_data: No payload to pass to upper layers"); + } + // Pass it to the ports if any + // params.log(); + to_all_upper_ports(p, params); +} + +btp_layer_factory btp_layer_factory::_f; diff --git a/ccsrc/Protocols/BTP/btp_layer.hh b/ccsrc/Protocols/BTP/btp_layer.hh index 7a8018868a37f2c28af76717f62d223eec77cd51..daaef45d623cd1c179118ad9a3d0e8dfc7b892a3 100644 --- a/ccsrc/Protocols/BTP/btp_layer.hh +++ b/ccsrc/Protocols/BTP/btp_layer.hh @@ -1,69 +1,69 @@ -/*! - * \file btp_layer.hh - * \brief Header file for ITS BTP protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "btp_codec.hh" -#include "t_layer.hh" - -namespace LibItsBtp__TestSystem { - class BtpPort; //! Forward declaration of TITAN class - class BtpReq; //! Forward declaration of TITAN class - class BtpInd; //! Forward declaration of TITAN class -} // namespace LibItsBtp__TestSystem - -/*! - * \class btp_layer - * \brief This class provides description of ITS BTP protocol layer - */ -class btp_layer : public t_layer { - params _params; //! Layer parameters - btp_codec _codec; //! BTP codec - bool _device_mode; //! Set to true if the BTP layer shall encapsulate the upper layer PDU -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the btp_layer class - */ - explicit btp_layer() : t_layer(), _params(), _codec(), _device_mode{false} {}; - /*! - * \brief Specialised constructor - * Create a new instance of the btp_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - btp_layer(const std::string &p_type, const std::string ¶m); - virtual ~btp_layer(){}; - - /*! - * \fn void sendMsg(const LibItsBtp__TestSystem::BtpReq& p_btp_req, params& p_param); - * \brief Send BTP message to the lower layers - * \param[in] p_btp_req The BTP message to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - void sendMsg(const LibItsBtp__TestSystem::BtpReq &p_btp_req, params &p_param); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class btp_layer +/*! + * \file btp_layer.hh + * \brief Header file for ITS BTP protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "btp_codec.hh" +#include "t_layer.hh" + +namespace LibItsBtp__TestSystem { + class BtpPort; //! Forward declaration of TITAN class + class BtpReq; //! Forward declaration of TITAN class + class BtpInd; //! Forward declaration of TITAN class +} // namespace LibItsBtp__TestSystem + +/*! + * \class btp_layer + * \brief This class provides description of ITS BTP protocol layer + */ +class btp_layer : public t_layer { + params _params; //! Layer parameters + btp_codec _codec; //! BTP codec + bool _device_mode; //! Set to true if the BTP layer shall encapsulate the upper layer PDU +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the btp_layer class + */ + explicit btp_layer() : t_layer(), _params(), _codec(), _device_mode{false} {}; + /*! + * \brief Specialised constructor + * Create a new instance of the btp_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + btp_layer(const std::string &p_type, const std::string ¶m); + virtual ~btp_layer(){}; + + /*! + * \fn void sendMsg(const LibItsBtp__TestSystem::BtpReq& p_btp_req, params& p_param); + * \brief Send BTP message to the lower layers + * \param[in] p_btp_req The BTP message to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + void sendMsg(const LibItsBtp__TypesAndValues::BtpReq &p_btp_req, params &p_param); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class btp_layer diff --git a/ccsrc/Protocols/BTP/btp_layer_factory.hh b/ccsrc/Protocols/BTP/btp_layer_factory.hh index 74a7dde156d757fee868f276709cd29f484a7cca..e2fa996866c1b934b86c4f667efe1918682228da 100644 --- a/ccsrc/Protocols/BTP/btp_layer_factory.hh +++ b/ccsrc/Protocols/BTP/btp_layer_factory.hh @@ -1,41 +1,41 @@ -/*! - * \file btp_layer_factory.hh - * \brief Header file for ITS BTP protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "btp_layer.hh" - -/*! - * \class cam_layer_factory - * \brief This class provides a factory class to create a btp_layer class instance - */ -class btp_layer_factory : public layer_factory { - static btp_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the btp_layer_factory class - * \remark The BTP layer identifier is BTP - */ - btp_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("BTP", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new btp_layer(p_type, p_param); }; -}; // End of class btp_layer_factory +/*! + * \file btp_layer_factory.hh + * \brief Header file for ITS BTP protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "btp_layer.hh" + +/*! + * \class cam_layer_factory + * \brief This class provides a factory class to create a btp_layer class instance + */ +class btp_layer_factory : public layer_factory { + static btp_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the btp_layer_factory class + * \remark The BTP layer identifier is BTP + */ + btp_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("BTP", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new btp_layer(p_type, p_param); }; +}; // End of class btp_layer_factory diff --git a/ccsrc/Protocols/BTP/btp_types.hh b/ccsrc/Protocols/BTP/btp_types.hh index e162b0b24d3b238a3c9d73d8e8c19dc287f587b1..59097c6253780438012b34d2cd28f03a858bfe5c 100644 --- a/ccsrc/Protocols/BTP/btp_types.hh +++ b/ccsrc/Protocols/BTP/btp_types.hh @@ -1,15 +1,15 @@ -/*! - * \file btp_types.hh - * \brief Header file for TITAN BTP types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsBtp_TestSystem.hh" -#include "LibItsBtp_TypesAndValues.hh" +/*! + * \file btp_types.hh + * \brief Header file for TITAN BTP types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsBtp_TestSystem.hh" +#include "LibItsBtp_TypesAndValues.hh" diff --git a/ccsrc/Protocols/BTP/module.mk b/ccsrc/Protocols/BTP/module.mk index b2a669340d7a9fe1e81403f50b5ab465d1df9085..5e4512488bdca95883ce7a44af5a7163f03d1073 100644 --- a/ccsrc/Protocols/BTP/module.mk +++ b/ccsrc/Protocols/BTP/module.mk @@ -1,2 +1,2 @@ -sources := btp_codec.cc btp_layer.cc +sources := btp_codec.cc btp_layer.cc includes := . \ No newline at end of file diff --git a/ccsrc/Protocols/CAM/cam_codec.cc b/ccsrc/Protocols/CAM/cam_codec.cc index 0e720d61822dcb82c8362266c718ac9b45fe3cdf..51eae463789c1b82fc5291e542982754beca0084 100644 --- a/ccsrc/Protocols/CAM/cam_codec.cc +++ b/ccsrc/Protocols/CAM/cam_codec.cc @@ -1,27 +1,27 @@ -#include "cam_codec.hh" -#include "LibItsCam_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int cam_codec::encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data) { - loggers::get_instance().log(">>> cam_codec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(cam, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("cam_codec::encode: ", data); - } - return rc; -} - -int cam_codec::decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &cam, params *params) { - loggers::get_instance().log_msg(">>> cam_codec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), cam); - loggers::get_instance().log("cam_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("cam_codec::decode: ", cam); - } - return rc; -} +#include "cam_codec.hh" +#include "LibItsCam_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int cam_codec::encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data) { + loggers::get_instance().log(">>> cam_codec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(cam, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("cam_codec::encode: ", data); + } + return rc; +} + +int cam_codec::decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &cam, params *params) { + loggers::get_instance().log_msg(">>> cam_codec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), cam); + loggers::get_instance().log("cam_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("cam_codec::decode: ", cam); + } + return rc; +} diff --git a/ccsrc/Protocols/CAM/cam_codec.hh b/ccsrc/Protocols/CAM/cam_codec.hh index 164ab6aa66830701545fbf35d3452aa3aa479434..0e5b5e4e8deea6a442e3666e7ac2425348b9f782 100644 --- a/ccsrc/Protocols/CAM/cam_codec.hh +++ b/ccsrc/Protocols/CAM/cam_codec.hh @@ -1,23 +1,23 @@ -#pragma once - -#include "cam_pdu_codec.hh" -#include "codec.hh" -#include "params.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class - class CAM; -} - -class cam_codec : public codec { - cam_pdu_codec asn_codec; - -public: - explicit cam_codec() : codec(), asn_codec(){}; - virtual ~cam_codec(){}; - - virtual int encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &, params *params = NULL); -}; +#pragma once + +#include "cam_pdu_codec.hh" +#include "codec.hh" +#include "params.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class + class CAM; +} + +class cam_codec : public codec { + cam_pdu_codec asn_codec; + +public: + explicit cam_codec() : codec(), asn_codec(){}; + virtual ~cam_codec(){}; + + virtual int encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &, params *params = NULL); +}; diff --git a/ccsrc/Protocols/CAM/cam_layer.cc b/ccsrc/Protocols/CAM/cam_layer.cc index a899804a59ec7cad16a17b4a15ea598edda9bf29..8b751d86c9c665e75459f7d22cbb58f8f1058530 100644 --- a/ccsrc/Protocols/CAM/cam_layer.cc +++ b/ccsrc/Protocols/CAM/cam_layer.cc @@ -1,147 +1,147 @@ -#include "cam_types.hh" - -#include "cam_layer_factory.hh" - -#include "registration.hh" - -#include "loggers.hh" - -cam_layer::cam_layer(const std::string &p_type, const std::string ¶m) : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> cam_layer::cam_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - _params.insert(std::make_pair("its_aid", "36")); // ETSI TS 102 965 V1.2.1 (2015-06) - _params.insert(std::make_pair("payload_type", "2")); // CA message id - See ETSI TS 102 894 - - // Register this object for AdapterControlPort - loggers::get_instance().log("cam_layer::cam_layer: Register %s/%p", p_type.c_str(), this); - registration::get_instance().add_item(p_type, this); -} - -void cam_layer::sendMsg(const LibItsCam__TestSystem::CamReq &p, params ¶ms) { - loggers::get_instance().log_msg(">>> cam_layer::sendMsg: ", p); - - // Encode CAM PDU - OCTETSTRING data; - if (_codec.encode(p.msgOut(), data) == -1) { - loggers::get_instance().warning("cam_layer::sendMsg: Encoding failure"); - return; - } - - send_data(data, _params); -} - -void cam_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> cam_layer::send_data: ", data); - - send_to_all_layers(data, params); -} - -void cam_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> cam_layer::receive_data: ", data); - - // Sanity check - if (*(static_cast(data) + 1) != 0x02) { // Check that received packet has CA message id - See ETSI TS 102 894 - // Not a CAM message, discard it - loggers::get_instance().warning("cam_layer::receive_data: Wrong message id: 0x%02x", *(static_cast(data) + 1)); - return; - } - - // Decode the payload - LibItsCam__TestSystem::CamInd p; - _codec.decode(data, p.msgIn()); - if (!p.msgIn().is_bound()) { - // Discard it - return; - } // else, continue - - // Process lower layer data - // recvTime - params::const_iterator it = params.find(params::timestamp); - if (it != params.cend()) { - p.recvTime().set_long_long_val(std::stoll(it->second)); - } else { - p.recvTime().set_to_omit(); - } - // gnNextHeader - it = params.find(params::gn_next_header); - if (it != params.cend()) { - p.gnNextHeader() = std::stoi(it->second); - } else { - p.gnNextHeader().set_to_omit(); - } - // gnHeaderType - it = params.find(params::gn_header_type); - if (it != params.cend()) { - p.gnHeaderType() = std::stoi(it->second); - } else { - p.gnHeaderType().set_to_omit(); - } - // gnHeaderSubtype - it = params.find(params::gn_header_sub_type); - if (it != params.cend()) { - p.gnHeaderSubtype() = std::stoi(it->second); - } else { - p.gnHeaderSubtype().set_to_omit(); - } - // gnLifetime - it = params.find(params::gn_lifetime); - if (it != params.cend()) { - p.gnLifetime() = std::stoi(it->second); - } else { - p.gnLifetime().set_to_omit(); - } - // gnTrafficClass - it = params.find(params::gn_traffic_class); - if (it != params.cend()) { - p.gnTrafficClass() = std::stoi(it->second); - } else { - p.gnTrafficClass().set_to_omit(); - } - // btpDestinationPort - it = params.find(params::btp_destination_port); - if (it != params.cend()) { - p.btpDestinationPort() = std::stoi(it->second); - } else { - p.btpDestinationPort().set_to_omit(); - } - // btpInfo - it = params.find(params::btp_info); - if (it != params.cend()) { - p.btpInfo() = std::stoi(it->second); - } else { - p.btpInfo().set_to_omit(); - } - // ssp - it = params.find(params::ssp); - if (it != params.cend()) { - loggers::get_instance().log("cam_layer::receive_data: ssp=%s", it->second.c_str()); - p.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); - } else { - p.ssp().set_to_omit(); - } - // its_aid - it = params.find(params::its_aid); - if (it != params.cend()) { - p.its__aid() = std::stoi(it->second); - } else { - p.its__aid().set_to_omit(); - } - - // Pass it to the ports if any - to_all_upper_ports(p, params); -} - -int cam_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { - loggers::get_instance().log(">>> cam_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); - - return 0; -} - -int cam_layer::disable_secured_mode() { - loggers::get_instance().log(">>> cam_layer::disable_secured_mode"); - - return 0; -} - -cam_layer_factory cam_layer_factory::_f; +#include "cam_types.hh" + +#include "cam_layer_factory.hh" + +#include "registration.hh" + +#include "loggers.hh" + +cam_layer::cam_layer(const std::string &p_type, const std::string ¶m) : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> cam_layer::cam_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + _params.insert(std::make_pair("its_aid", "36")); // ETSI TS 102 965 V1.2.1 (2015-06) + _params.insert(std::make_pair("payload_type", "2")); // CA message id - See ETSI TS 102 894 + + // Register this object for AdapterControlPort + loggers::get_instance().log("cam_layer::cam_layer: Register %s/%p", p_type.c_str(), this); + registration::get_instance().add_item(p_type, this); +} + +void cam_layer::sendMsg(const LibItsCam__TestSystem::CamReq &p, params ¶ms) { + loggers::get_instance().log_msg(">>> cam_layer::sendMsg: ", p); + + // Encode CAM PDU + OCTETSTRING data; + if (_codec.encode(p.msgOut(), data) == -1) { + loggers::get_instance().warning("cam_layer::sendMsg: Encoding failure"); + return; + } + + send_data(data, _params); +} + +void cam_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> cam_layer::send_data: ", data); + + send_to_all_layers(data, params); +} + +void cam_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> cam_layer::receive_data: ", data); + + // Sanity check + if (*(static_cast(data) + 1) != 0x02) { // Check that received packet has CA message id - See ETSI TS 102 894 + // Not a CAM message, discard it + loggers::get_instance().warning("cam_layer::receive_data: Wrong message id: 0x%02x", *(static_cast(data) + 1)); + return; + } + + // Decode the payload + LibItsCam__TestSystem::CamInd p; + _codec.decode(data, p.msgIn()); + if (!p.msgIn().is_bound()) { + // Discard it + return; + } // else, continue + + // Process lower layer data + // recvTime + params::const_iterator it = params.find(params::timestamp); + if (it != params.cend()) { + p.recvTime().set_long_long_val(std::stoll(it->second)); + } else { + p.recvTime().set_to_omit(); + } + // gnNextHeader + it = params.find(params::gn_next_header); + if (it != params.cend()) { + p.gnNextHeader() = std::stoi(it->second); + } else { + p.gnNextHeader().set_to_omit(); + } + // gnHeaderType + it = params.find(params::gn_header_type); + if (it != params.cend()) { + p.gnHeaderType() = std::stoi(it->second); + } else { + p.gnHeaderType().set_to_omit(); + } + // gnHeaderSubtype + it = params.find(params::gn_header_sub_type); + if (it != params.cend()) { + p.gnHeaderSubtype() = std::stoi(it->second); + } else { + p.gnHeaderSubtype().set_to_omit(); + } + // gnLifetime + it = params.find(params::gn_lifetime); + if (it != params.cend()) { + p.gnLifetime() = std::stoi(it->second); + } else { + p.gnLifetime().set_to_omit(); + } + // gnTrafficClass + it = params.find(params::gn_traffic_class); + if (it != params.cend()) { + p.gnTrafficClass() = std::stoi(it->second); + } else { + p.gnTrafficClass().set_to_omit(); + } + // btpDestinationPort + it = params.find(params::btp_destination_port); + if (it != params.cend()) { + p.btpDestinationPort() = std::stoi(it->second); + } else { + p.btpDestinationPort().set_to_omit(); + } + // btpInfo + it = params.find(params::btp_info); + if (it != params.cend()) { + p.btpInfo() = std::stoi(it->second); + } else { + p.btpInfo().set_to_omit(); + } + // ssp + it = params.find(params::ssp); + if (it != params.cend()) { + loggers::get_instance().log("cam_layer::receive_data: ssp=%s", it->second.c_str()); + p.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); + } else { + p.ssp().set_to_omit(); + } + // its_aid + it = params.find(params::its_aid); + if (it != params.cend()) { + p.its__aid() = std::stoi(it->second); + } else { + p.its__aid().set_to_omit(); + } + + // Pass it to the ports if any + to_all_upper_ports(p, params); +} + +int cam_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { + loggers::get_instance().log(">>> cam_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); + + return 0; +} + +int cam_layer::disable_secured_mode() { + loggers::get_instance().log(">>> cam_layer::disable_secured_mode"); + + return 0; +} + +cam_layer_factory cam_layer_factory::_f; diff --git a/ccsrc/Protocols/CAM/cam_layer.hh b/ccsrc/Protocols/CAM/cam_layer.hh index 23fd146b7329d3268a9c2975aeaea2c61f4da5e4..810a4167a18f57fe0f379674e4ee20c13cf536fc 100644 --- a/ccsrc/Protocols/CAM/cam_layer.hh +++ b/ccsrc/Protocols/CAM/cam_layer.hh @@ -1,76 +1,76 @@ -/*! - * \file cam_layer.hh - * \brief Header file for ITS CAM protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "cam_codec.hh" -#include "t_layer.hh" - -namespace LibItsCam__TestSystem { - class CamPort; //! Forward declaration of TITAN class - class CamReq; //! Forward declaration of TITAN class - class CamInd; //! Forward declaration of TITAN class -} // namespace LibItsCam__TestSystem - -/*! - * \class cam_layer - * \brief This class provides description of ITS CAM protocol layer - */ -class cam_layer : public t_layer { - params _params; //! Layer parameters - cam_codec _codec; //! CAM codec -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the cam_layer class - */ - explicit cam_layer() : t_layer(), _params(), _codec(){}; - /*! - * \brief Specialised constructor - * Create a new instance of the cam_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - cam_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~cam_layer(){}; - - /*! - * \fn void sendMsg(const LibItsCam__TestSystem::CamReq& p_cam_req, params& p_params); - * \brief Send CA message to the lower layers - * \param[in] p_cam_req The CA message to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - void sendMsg(const LibItsCam__TestSystem::CamReq &p_cam_req, params &p_params); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security); - - int disable_secured_mode(); - -}; // End of class cam_layer +/*! + * \file cam_layer.hh + * \brief Header file for ITS CAM protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "cam_codec.hh" +#include "t_layer.hh" + +namespace LibItsCam__TestSystem { + class CamPort; //! Forward declaration of TITAN class + class CamReq; //! Forward declaration of TITAN class + class CamInd; //! Forward declaration of TITAN class +} // namespace LibItsCam__TestSystem + +/*! + * \class cam_layer + * \brief This class provides description of ITS CAM protocol layer + */ +class cam_layer : public t_layer { + params _params; //! Layer parameters + cam_codec _codec; //! CAM codec +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the cam_layer class + */ + explicit cam_layer() : t_layer(), _params(), _codec(){}; + /*! + * \brief Specialised constructor + * Create a new instance of the cam_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + cam_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~cam_layer(){}; + + /*! + * \fn void sendMsg(const LibItsCam__TestSystem::CamReq& p_cam_req, params& p_params); + * \brief Send CA message to the lower layers + * \param[in] p_cam_req The CA message to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + void sendMsg(const LibItsCam__TestSystem::CamReq &p_cam_req, params &p_params); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security); + + int disable_secured_mode(); + +}; // End of class cam_layer diff --git a/ccsrc/Protocols/CAM/cam_layer_factory.hh b/ccsrc/Protocols/CAM/cam_layer_factory.hh index f37aafc04ebda2eb646fd092ae4e0f544704fc5b..07b7862d9817480ee140597e33749de0a6a6da31 100644 --- a/ccsrc/Protocols/CAM/cam_layer_factory.hh +++ b/ccsrc/Protocols/CAM/cam_layer_factory.hh @@ -1,41 +1,41 @@ -/*! - * \file cam_layer_factory.hh - * \brief Header file for ITS CAM protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "cam_layer.hh" - -/*! - * \class cam_layer_factory - * \brief This class provides a factory class to create a cam_layer class instance - */ -class cam_layer_factory : public layer_factory { - static cam_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the cam_layer_factory class - * \remark The CAM layer identifier is CAM - */ - cam_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("CAM", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new cam_layer(p_type, p_param); }; -}; // End of class cam_layer_factory +/*! + * \file cam_layer_factory.hh + * \brief Header file for ITS CAM protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "cam_layer.hh" + +/*! + * \class cam_layer_factory + * \brief This class provides a factory class to create a cam_layer class instance + */ +class cam_layer_factory : public layer_factory { + static cam_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the cam_layer_factory class + * \remark The CAM layer identifier is CAM + */ + cam_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("CAM", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new cam_layer(p_type, p_param); }; +}; // End of class cam_layer_factory diff --git a/ccsrc/Protocols/CAM/cam_pdu_codec.cc b/ccsrc/Protocols/CAM/cam_pdu_codec.cc index 412de56c7cda8dca07852bcccd150c5f635cefa7..53e3e2c4cd0ca82d8282bfc09a9dd4cd1c050597 100644 --- a/ccsrc/Protocols/CAM/cam_pdu_codec.cc +++ b/ccsrc/Protocols/CAM/cam_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "cam_pdu_codec.hh" -#include "LibItsCam_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_CAM; -} - -int cam_pdu_codec::encode(const CAM__PDU__Descriptions::CAM &p_cam, BITSTRING &p_data) { - return _encode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_cam, p_data); -} - -int cam_pdu_codec::decode(const BITSTRING &p_data, CAM__PDU__Descriptions::CAM &p_cam) { - return _decode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_data, p_cam); -} +#include "cam_pdu_codec.hh" +#include "LibItsCam_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_CAM; +} + +int cam_pdu_codec::encode(const CAM__PDU__Descriptions::CAM &p_cam, BITSTRING &p_data) { + return _encode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_cam, p_data); +} + +int cam_pdu_codec::decode(const BITSTRING &p_data, CAM__PDU__Descriptions::CAM &p_cam) { + return _decode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_data, p_cam); +} diff --git a/ccsrc/Protocols/CAM/cam_pdu_codec.hh b/ccsrc/Protocols/CAM/cam_pdu_codec.hh index 4e78521d8741a5c65ec10c02bb3a2e814c99e2b1..8a924af8068146bd011409beb489f1333a80b64f 100644 --- a/ccsrc/Protocols/CAM/cam_pdu_codec.hh +++ b/ccsrc/Protocols/CAM/cam_pdu_codec.hh @@ -1,19 +1,19 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class - class CAM; -} - -class cam_pdu_codec : public per_codec { -public: - explicit cam_pdu_codec(){}; - virtual int encode(const CAM__PDU__Descriptions::CAM &cam, BITSTRING &data); - virtual int decode(const BITSTRING &data, CAM__PDU__Descriptions::CAM &); -}; +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class + class CAM; +} + +class cam_pdu_codec : public per_codec { +public: + explicit cam_pdu_codec(){}; + virtual int encode(const CAM__PDU__Descriptions::CAM &cam, BITSTRING &data); + virtual int decode(const BITSTRING &data, CAM__PDU__Descriptions::CAM &); +}; diff --git a/ccsrc/Protocols/CAM/cam_types.hh b/ccsrc/Protocols/CAM/cam_types.hh index 4750d596ee20d8b142d86aa2e862939005c536e8..0a3daeed0997a65e280ad3594c5bb00b3aa06d7a 100644 --- a/ccsrc/Protocols/CAM/cam_types.hh +++ b/ccsrc/Protocols/CAM/cam_types.hh @@ -1,15 +1,15 @@ -/*! - * \file cam_types.hh - * \brief Header file for TITAN CAM types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsCam_TestSystem.hh" -#include "LibItsCam_TypesAndValues.hh" +/*! + * \file cam_types.hh + * \brief Header file for TITAN CAM types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsCam_TestSystem.hh" +#include "LibItsCam_TypesAndValues.hh" diff --git a/ccsrc/Protocols/CAM/module.mk b/ccsrc/Protocols/CAM/module.mk index 0a2ec4c64d3fbef547a4dc66cbe8b980615cba3f..263c28e39b0e42604cb928a3dfa3c03277e2285f 100644 --- a/ccsrc/Protocols/CAM/module.mk +++ b/ccsrc/Protocols/CAM/module.mk @@ -1,2 +1,2 @@ -sources := cam_codec.cc cam_layer.cc cam_pdu_codec.cc +sources := cam_codec.cc cam_layer.cc cam_pdu_codec.cc includes := . \ No newline at end of file diff --git a/ccsrc/Protocols/CAM_Codecs/cam_codec.cc b/ccsrc/Protocols/CAM_Codecs/cam_codec.cc index 15685d04e3f500bb73f495a81c980bf1e521deb3..40f9ea9f6a229aec2118f7b122f198292331970c 100644 --- a/ccsrc/Protocols/CAM_Codecs/cam_codec.cc +++ b/ccsrc/Protocols/CAM_Codecs/cam_codec.cc @@ -1,28 +1,28 @@ -#include "LibItsCam_TypesAndValues.hh" - -#include "cam_codec.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int cam_codec::encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data) { - loggers::get_instance().log(">>> cam_codec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(cam, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("cam_codec::encode: ", data); - } - return rc; -} - -int cam_codec::decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &cam, params *params) { - loggers::get_instance().log_msg(">>> cam_codec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), cam); - loggers::get_instance().log("cam_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("cam_codec::decode: ", cam); - } - return rc; -} +#include "LibItsCam_TypesAndValues.hh" + +#include "cam_codec.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int cam_codec::encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data) { + loggers::get_instance().log(">>> cam_codec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(cam, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("cam_codec::encode: ", data); + } + return rc; +} + +int cam_codec::decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &cam, params *params) { + loggers::get_instance().log_msg(">>> cam_codec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), cam); + loggers::get_instance().log("cam_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("cam_codec::decode: ", cam); + } + return rc; +} diff --git a/ccsrc/Protocols/CAM_Codecs/cam_codec.hh b/ccsrc/Protocols/CAM_Codecs/cam_codec.hh index 164ab6aa66830701545fbf35d3452aa3aa479434..0e5b5e4e8deea6a442e3666e7ac2425348b9f782 100644 --- a/ccsrc/Protocols/CAM_Codecs/cam_codec.hh +++ b/ccsrc/Protocols/CAM_Codecs/cam_codec.hh @@ -1,23 +1,23 @@ -#pragma once - -#include "cam_pdu_codec.hh" -#include "codec.hh" -#include "params.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class - class CAM; -} - -class cam_codec : public codec { - cam_pdu_codec asn_codec; - -public: - explicit cam_codec() : codec(), asn_codec(){}; - virtual ~cam_codec(){}; - - virtual int encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &, params *params = NULL); -}; +#pragma once + +#include "cam_pdu_codec.hh" +#include "codec.hh" +#include "params.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class + class CAM; +} + +class cam_codec : public codec { + cam_pdu_codec asn_codec; + +public: + explicit cam_codec() : codec(), asn_codec(){}; + virtual ~cam_codec(){}; + + virtual int encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &, params *params = NULL); +}; diff --git a/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.cc b/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.cc index 77fedd34a3bd2632530e86d650c46c47f16a5b86..457e3feaff4669babae37e3ffa916a4d3855a06d 100644 --- a/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.cc +++ b/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "cam_pdu_codec.hh" -#include "LibItsCam_TypesAndValues.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_CAM; -} - -int cam_pdu_codec::encode(const CAM__PDU__Descriptions::CAM &p_cam, BITSTRING &p_data) { - return _encode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_cam, p_data); -} - -int cam_pdu_codec::decode(const BITSTRING &p_data, CAM__PDU__Descriptions::CAM &p_cam) { - return _decode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_data, p_cam); -} +#include "cam_pdu_codec.hh" +#include "LibItsCam_TypesAndValues.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_CAM; +} + +int cam_pdu_codec::encode(const CAM__PDU__Descriptions::CAM &p_cam, BITSTRING &p_data) { + return _encode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_cam, p_data); +} + +int cam_pdu_codec::decode(const BITSTRING &p_data, CAM__PDU__Descriptions::CAM &p_cam) { + return _decode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_data, p_cam); +} diff --git a/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.hh b/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.hh index 4e78521d8741a5c65ec10c02bb3a2e814c99e2b1..8a924af8068146bd011409beb489f1333a80b64f 100644 --- a/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.hh +++ b/ccsrc/Protocols/CAM_Codecs/cam_pdu_codec.hh @@ -1,19 +1,19 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class - class CAM; -} - -class cam_pdu_codec : public per_codec { -public: - explicit cam_pdu_codec(){}; - virtual int encode(const CAM__PDU__Descriptions::CAM &cam, BITSTRING &data); - virtual int decode(const BITSTRING &data, CAM__PDU__Descriptions::CAM &); -}; +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class + class CAM; +} + +class cam_pdu_codec : public per_codec { +public: + explicit cam_pdu_codec(){}; + virtual int encode(const CAM__PDU__Descriptions::CAM &cam, BITSTRING &data); + virtual int decode(const BITSTRING &data, CAM__PDU__Descriptions::CAM &); +}; diff --git a/ccsrc/Protocols/CAM_Codecs/cam_types.hh b/ccsrc/Protocols/CAM_Codecs/cam_types.hh index e8bc41810e42b1e128d1fefae8bf0524e2bbc069..b561fac5d9e2b4157c56b39f88000af5c0792498 100644 --- a/ccsrc/Protocols/CAM_Codecs/cam_types.hh +++ b/ccsrc/Protocols/CAM_Codecs/cam_types.hh @@ -1,14 +1,14 @@ -/*! - * \file cam_types.hh - * \brief Header file for TITAN CAM types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsCam_TypesAndValues.hh" +/*! + * \file cam_types.hh + * \brief Header file for TITAN CAM types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsCam_TypesAndValues.hh" diff --git a/ccsrc/Protocols/CAM_Codecs/module.mk b/ccsrc/Protocols/CAM_Codecs/module.mk index 049b63d5ac0cd43fe0c6b143b06049dfd86ec7e1..138aaaf63a71548533c8861f156b68c345cd7d5f 100644 --- a/ccsrc/Protocols/CAM_Codecs/module.mk +++ b/ccsrc/Protocols/CAM_Codecs/module.mk @@ -1,2 +1,2 @@ -sources := cam_codec.cc cam_pdu_codec.cc -includes := . +sources := cam_codec.cc cam_pdu_codec.cc +includes := . diff --git a/ccsrc/Protocols/CAM_Layers/cam_codec.cc b/ccsrc/Protocols/CAM_Layers/cam_codec.cc index 15685d04e3f500bb73f495a81c980bf1e521deb3..40f9ea9f6a229aec2118f7b122f198292331970c 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_codec.cc +++ b/ccsrc/Protocols/CAM_Layers/cam_codec.cc @@ -1,28 +1,28 @@ -#include "LibItsCam_TypesAndValues.hh" - -#include "cam_codec.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int cam_codec::encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data) { - loggers::get_instance().log(">>> cam_codec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(cam, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("cam_codec::encode: ", data); - } - return rc; -} - -int cam_codec::decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &cam, params *params) { - loggers::get_instance().log_msg(">>> cam_codec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), cam); - loggers::get_instance().log("cam_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("cam_codec::decode: ", cam); - } - return rc; -} +#include "LibItsCam_TypesAndValues.hh" + +#include "cam_codec.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int cam_codec::encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data) { + loggers::get_instance().log(">>> cam_codec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(cam, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("cam_codec::encode: ", data); + } + return rc; +} + +int cam_codec::decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &cam, params *params) { + loggers::get_instance().log_msg(">>> cam_codec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), cam); + loggers::get_instance().log("cam_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("cam_codec::decode: ", cam); + } + return rc; +} diff --git a/ccsrc/Protocols/CAM_Layers/cam_codec.hh b/ccsrc/Protocols/CAM_Layers/cam_codec.hh index 164ab6aa66830701545fbf35d3452aa3aa479434..0e5b5e4e8deea6a442e3666e7ac2425348b9f782 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_codec.hh +++ b/ccsrc/Protocols/CAM_Layers/cam_codec.hh @@ -1,23 +1,23 @@ -#pragma once - -#include "cam_pdu_codec.hh" -#include "codec.hh" -#include "params.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class - class CAM; -} - -class cam_codec : public codec { - cam_pdu_codec asn_codec; - -public: - explicit cam_codec() : codec(), asn_codec(){}; - virtual ~cam_codec(){}; - - virtual int encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &, params *params = NULL); -}; +#pragma once + +#include "cam_pdu_codec.hh" +#include "codec.hh" +#include "params.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class + class CAM; +} + +class cam_codec : public codec { + cam_pdu_codec asn_codec; + +public: + explicit cam_codec() : codec(), asn_codec(){}; + virtual ~cam_codec(){}; + + virtual int encode(const CAM__PDU__Descriptions::CAM &cam, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, CAM__PDU__Descriptions::CAM &, params *params = NULL); +}; diff --git a/ccsrc/Protocols/CAM_Layers/cam_layer.cc b/ccsrc/Protocols/CAM_Layers/cam_layer.cc index 86bbc4a7d2b288581701272d98842de14d420f23..a0748d08013b2bbcb7acba1464661390e83fbbf9 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_layer.cc +++ b/ccsrc/Protocols/CAM_Layers/cam_layer.cc @@ -1,147 +1,147 @@ -#include "cam_types.hh" - -#include "cam_layer_factory.hh" - -#include "registration.hh" - -#include "loggers.hh" - -cam_layer::cam_layer(const std::string &p_type, const std::string ¶m) : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> cam_layer::cam_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - _params.insert(std::make_pair("its_aid", "36")); // ETSI TS 102 965 V1.2.1 (2015-06) - _params.insert(std::make_pair("payload_type", "2")); // CA message id - See ETSI TS 102 894 - - // Register this object for AdapterControlPort - loggers::get_instance().log("cam_layer::cam_layer: Register %s/%p", p_type.c_str(), this); - registration::get_instance().add_item(p_type, this); -} - -void cam_layer::sendMsg(const LibItsCam__TypesAndValues::CamReq &p, params ¶ms) { - loggers::get_instance().log_msg(">>> cam_layer::sendMsg: ", p); - - // Encode CAM PDU - OCTETSTRING data; - if (_codec.encode(p.msgOut(), data) == -1) { - loggers::get_instance().warning("cam_layer::sendMsg: Encoding failure"); - return; - } - - send_data(data, _params); -} - -void cam_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> cam_layer::send_data: ", data); - - send_to_all_layers(data, params); -} - -void cam_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> cam_layer::receive_data: ", data); - - // Sanity check - if (*(static_cast(data) + 1) != 0x02) { // Check that received packet has CA message id - See ETSI TS 102 894 - // Not a CAM message, discard it - loggers::get_instance().warning("cam_layer::receive_data: Wrong message id: 0x%02x", *(static_cast(data) + 1)); - return; - } - - // Decode the payload - LibItsCam__TypesAndValues::CamInd p; - _codec.decode(data, p.msgIn()); - if (!p.msgIn().is_bound()) { - // Discard it - return; - } // else, continue - - // Process lower layer data - // recvTime - params::const_iterator it = params.find(params::timestamp); - if (it != params.cend()) { - p.recvTime().set_long_long_val(std::stoll(it->second)); - } else { - p.recvTime().set_to_omit(); - } - // gnNextHeader - it = params.find(params::gn_next_header); - if (it != params.cend()) { - p.gnNextHeader() = std::stoi(it->second); - } else { - p.gnNextHeader().set_to_omit(); - } - // gnHeaderType - it = params.find(params::gn_header_type); - if (it != params.cend()) { - p.gnHeaderType() = std::stoi(it->second); - } else { - p.gnHeaderType().set_to_omit(); - } - // gnHeaderSubtype - it = params.find(params::gn_header_sub_type); - if (it != params.cend()) { - p.gnHeaderSubtype() = std::stoi(it->second); - } else { - p.gnHeaderSubtype().set_to_omit(); - } - // gnLifetime - it = params.find(params::gn_lifetime); - if (it != params.cend()) { - p.gnLifetime() = std::stoi(it->second); - } else { - p.gnLifetime().set_to_omit(); - } - // gnTrafficClass - it = params.find(params::gn_traffic_class); - if (it != params.cend()) { - p.gnTrafficClass() = std::stoi(it->second); - } else { - p.gnTrafficClass().set_to_omit(); - } - // btpDestinationPort - it = params.find(params::btp_destination_port); - if (it != params.cend()) { - p.btpDestinationPort() = std::stoi(it->second); - } else { - p.btpDestinationPort().set_to_omit(); - } - // btpInfo - it = params.find(params::btp_info); - if (it != params.cend()) { - p.btpInfo() = std::stoi(it->second); - } else { - p.btpInfo().set_to_omit(); - } - // ssp - it = params.find(params::ssp); - if (it != params.cend()) { - loggers::get_instance().log("cam_layer::receive_data: ssp=%s", it->second.c_str()); - p.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); - } else { - p.ssp().set_to_omit(); - } - // its_aid - it = params.find(params::its_aid); - if (it != params.cend()) { - p.its__aid() = std::stoi(it->second); - } else { - p.its__aid().set_to_omit(); - } - - // Pass it to the ports if any - to_all_upper_ports(p, params); -} - -int cam_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { - loggers::get_instance().log(">>> cam_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); - - return 0; -} - -int cam_layer::disable_secured_mode() { - loggers::get_instance().log(">>> cam_layer::disable_secured_mode"); - - return 0; -} - -cam_layer_factory cam_layer_factory::_f; +#include "cam_types.hh" + +#include "cam_layer_factory.hh" + +#include "registration.hh" + +#include "loggers.hh" + +cam_layer::cam_layer(const std::string &p_type, const std::string ¶m) : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> cam_layer::cam_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + _params.insert(std::make_pair("its_aid", "36")); // ETSI TS 102 965 V1.2.1 (2015-06) + _params.insert(std::make_pair("payload_type", "2")); // CA message id - See ETSI TS 102 894 + + // Register this object for AdapterControlPort + loggers::get_instance().log("cam_layer::cam_layer: Register %s/%p", p_type.c_str(), this); + registration::get_instance().add_item(p_type, this); +} + +void cam_layer::sendMsg(const LibItsCam__TypesAndValues::CamReq &p, params ¶ms) { + loggers::get_instance().log_msg(">>> cam_layer::sendMsg: ", p); + + // Encode CAM PDU + OCTETSTRING data; + if (_codec.encode(p.msgOut(), data) == -1) { + loggers::get_instance().warning("cam_layer::sendMsg: Encoding failure"); + return; + } + + send_data(data, _params); +} + +void cam_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> cam_layer::send_data: ", data); + + send_to_all_layers(data, params); +} + +void cam_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> cam_layer::receive_data: ", data); + + // Sanity check + if (*(static_cast(data) + 1) != 0x02) { // Check that received packet has CA message id - See ETSI TS 102 894 + // Not a CAM message, discard it + loggers::get_instance().warning("cam_layer::receive_data: Wrong message id: 0x%02x", *(static_cast(data) + 1)); + return; + } + + // Decode the payload + LibItsCam__TypesAndValues::CamInd p; + _codec.decode(data, p.msgIn()); + if (!p.msgIn().is_bound()) { + // Discard it + return; + } // else, continue + + // Process lower layer data + // recvTime + params::const_iterator it = params.find(params::timestamp); + if (it != params.cend()) { + p.recvTime().set_long_long_val(std::stoll(it->second)); + } else { + p.recvTime().set_to_omit(); + } + // gnNextHeader + it = params.find(params::gn_next_header); + if (it != params.cend()) { + p.gnNextHeader() = std::stoi(it->second); + } else { + p.gnNextHeader().set_to_omit(); + } + // gnHeaderType + it = params.find(params::gn_header_type); + if (it != params.cend()) { + p.gnHeaderType() = std::stoi(it->second); + } else { + p.gnHeaderType().set_to_omit(); + } + // gnHeaderSubtype + it = params.find(params::gn_header_sub_type); + if (it != params.cend()) { + p.gnHeaderSubtype() = std::stoi(it->second); + } else { + p.gnHeaderSubtype().set_to_omit(); + } + // gnLifetime + it = params.find(params::gn_lifetime); + if (it != params.cend()) { + p.gnLifetime() = std::stoi(it->second); + } else { + p.gnLifetime().set_to_omit(); + } + // gnTrafficClass + it = params.find(params::gn_traffic_class); + if (it != params.cend()) { + p.gnTrafficClass() = std::stoi(it->second); + } else { + p.gnTrafficClass().set_to_omit(); + } + // btpDestinationPort + it = params.find(params::btp_destination_port); + if (it != params.cend()) { + p.btpDestinationPort() = std::stoi(it->second); + } else { + p.btpDestinationPort().set_to_omit(); + } + // btpInfo + it = params.find(params::btp_info); + if (it != params.cend()) { + p.btpInfo() = std::stoi(it->second); + } else { + p.btpInfo().set_to_omit(); + } + // ssp + it = params.find(params::ssp); + if (it != params.cend()) { + loggers::get_instance().log("cam_layer::receive_data: ssp=%s", it->second.c_str()); + p.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); + } else { + p.ssp().set_to_omit(); + } + // its_aid + it = params.find(params::its_aid); + if (it != params.cend()) { + p.its__aid() = std::stoi(it->second); + } else { + p.its__aid().set_to_omit(); + } + + // Pass it to the ports if any + to_all_upper_ports(p, params); +} + +int cam_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { + loggers::get_instance().log(">>> cam_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); + + return 0; +} + +int cam_layer::disable_secured_mode() { + loggers::get_instance().log(">>> cam_layer::disable_secured_mode"); + + return 0; +} + +cam_layer_factory cam_layer_factory::_f; diff --git a/ccsrc/Protocols/CAM_Layers/cam_layer.hh b/ccsrc/Protocols/CAM_Layers/cam_layer.hh index a8c02eaabb36383b6e131eb6511ddcb282c25a6c..288f9e79f3877e5140a1cbdaf1bf03d4c86c3dd5 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_layer.hh +++ b/ccsrc/Protocols/CAM_Layers/cam_layer.hh @@ -1,79 +1,79 @@ -/*! - * \file cam_layer.hh - * \brief Header file for ITS CAM protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "cam_codec.hh" -#include "t_layer.hh" - -namespace LibItsCam__TestSystem { - class CamPort; //! Forward declaration of TITAN class -} // namespace LibItsCam__TestSystem - -namespace LibItsCam__TypesAndValues { - class CamReq; //! Forward declaration of TITAN class - class CamInd; //! Forward declaration of TITAN class -} // namespace LibItsCam__TypesAndValues - -/*! - * \class cam_layer - * \brief This class provides description of ITS CAM protocol layer - */ -class cam_layer : public t_layer { - params _params; //! Layer parameters - cam_codec _codec; //! CAM codec -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the cam_layer class - */ - explicit cam_layer() : t_layer(), _params(), _codec(){}; - /*! - * \brief Specialised constructor - * Create a new instance of the cam_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - cam_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~cam_layer(){}; - - /*! - * \fn void sendMsg(const LibItsCam__TypesAndValues::CamReq& p_cam_req, params& p_params); - * \brief Send CA message to the lower layers - * \param[in] p_cam_req The CA message to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - void sendMsg(const LibItsCam__TypesAndValues::CamReq &p_cam_req, params &p_params); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security); - - int disable_secured_mode(); - -}; // End of class cam_layer +/*! + * \file cam_layer.hh + * \brief Header file for ITS CAM protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "cam_codec.hh" +#include "t_layer.hh" + +namespace LibItsCam__TestSystem { + class CamPort; //! Forward declaration of TITAN class +} // namespace LibItsCam__TestSystem + +namespace LibItsCam__TypesAndValues { + class CamReq; //! Forward declaration of TITAN class + class CamInd; //! Forward declaration of TITAN class +} // namespace LibItsCam__TypesAndValues + +/*! + * \class cam_layer + * \brief This class provides description of ITS CAM protocol layer + */ +class cam_layer : public t_layer { + params _params; //! Layer parameters + cam_codec _codec; //! CAM codec +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the cam_layer class + */ + explicit cam_layer() : t_layer(), _params(), _codec(){}; + /*! + * \brief Specialised constructor + * Create a new instance of the cam_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + cam_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~cam_layer(){}; + + /*! + * \fn void sendMsg(const LibItsCam__TypesAndValues::CamReq& p_cam_req, params& p_params); + * \brief Send CA message to the lower layers + * \param[in] p_cam_req The CA message to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + void sendMsg(const LibItsCam__TypesAndValues::CamReq &p_cam_req, params &p_params); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security); + + int disable_secured_mode(); + +}; // End of class cam_layer diff --git a/ccsrc/Protocols/CAM_Layers/cam_layer_factory.hh b/ccsrc/Protocols/CAM_Layers/cam_layer_factory.hh index f37aafc04ebda2eb646fd092ae4e0f544704fc5b..07b7862d9817480ee140597e33749de0a6a6da31 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_layer_factory.hh +++ b/ccsrc/Protocols/CAM_Layers/cam_layer_factory.hh @@ -1,41 +1,41 @@ -/*! - * \file cam_layer_factory.hh - * \brief Header file for ITS CAM protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "cam_layer.hh" - -/*! - * \class cam_layer_factory - * \brief This class provides a factory class to create a cam_layer class instance - */ -class cam_layer_factory : public layer_factory { - static cam_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the cam_layer_factory class - * \remark The CAM layer identifier is CAM - */ - cam_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("CAM", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new cam_layer(p_type, p_param); }; -}; // End of class cam_layer_factory +/*! + * \file cam_layer_factory.hh + * \brief Header file for ITS CAM protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "cam_layer.hh" + +/*! + * \class cam_layer_factory + * \brief This class provides a factory class to create a cam_layer class instance + */ +class cam_layer_factory : public layer_factory { + static cam_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the cam_layer_factory class + * \remark The CAM layer identifier is CAM + */ + cam_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("CAM", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new cam_layer(p_type, p_param); }; +}; // End of class cam_layer_factory diff --git a/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.cc b/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.cc index 412de56c7cda8dca07852bcccd150c5f635cefa7..53e3e2c4cd0ca82d8282bfc09a9dd4cd1c050597 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.cc +++ b/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "cam_pdu_codec.hh" -#include "LibItsCam_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_CAM; -} - -int cam_pdu_codec::encode(const CAM__PDU__Descriptions::CAM &p_cam, BITSTRING &p_data) { - return _encode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_cam, p_data); -} - -int cam_pdu_codec::decode(const BITSTRING &p_data, CAM__PDU__Descriptions::CAM &p_cam) { - return _decode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_data, p_cam); -} +#include "cam_pdu_codec.hh" +#include "LibItsCam_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_CAM; +} + +int cam_pdu_codec::encode(const CAM__PDU__Descriptions::CAM &p_cam, BITSTRING &p_data) { + return _encode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_cam, p_data); +} + +int cam_pdu_codec::decode(const BITSTRING &p_data, CAM__PDU__Descriptions::CAM &p_cam) { + return _decode(CAM__PDU__Descriptions::CAM_descr_, asn_DEF_CAM, p_data, p_cam); +} diff --git a/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.hh b/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.hh index 4e78521d8741a5c65ec10c02bb3a2e814c99e2b1..8a924af8068146bd011409beb489f1333a80b64f 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.hh +++ b/ccsrc/Protocols/CAM_Layers/cam_pdu_codec.hh @@ -1,19 +1,19 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -class BITSTRING; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class - class CAM; -} - -class cam_pdu_codec : public per_codec { -public: - explicit cam_pdu_codec(){}; - virtual int encode(const CAM__PDU__Descriptions::CAM &cam, BITSTRING &data); - virtual int decode(const BITSTRING &data, CAM__PDU__Descriptions::CAM &); -}; +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +class BITSTRING; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace CAM__PDU__Descriptions { //! Forward declaration of asn1c CAM class + class CAM; +} + +class cam_pdu_codec : public per_codec { +public: + explicit cam_pdu_codec(){}; + virtual int encode(const CAM__PDU__Descriptions::CAM &cam, BITSTRING &data); + virtual int decode(const BITSTRING &data, CAM__PDU__Descriptions::CAM &); +}; diff --git a/ccsrc/Protocols/CAM_Layers/cam_types.hh b/ccsrc/Protocols/CAM_Layers/cam_types.hh index f4b74d03b65a52e016cbbec3961427713fd8188b..148f97c2ce095dfd2e29e39725b58ae0c1168b7d 100644 --- a/ccsrc/Protocols/CAM_Layers/cam_types.hh +++ b/ccsrc/Protocols/CAM_Layers/cam_types.hh @@ -1,16 +1,16 @@ -/*! - * \file cam_types.hh - * \brief Header file for TITAN CAM types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsCam_TypesAndValues.hh" -#include "LibItsCam_TestSystem.hh" - +/*! + * \file cam_types.hh + * \brief Header file for TITAN CAM types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsCam_TypesAndValues.hh" +#include "LibItsCam_TestSystem.hh" + diff --git a/ccsrc/Protocols/CAM_Layers/module.mk b/ccsrc/Protocols/CAM_Layers/module.mk index 4c8139effac44eda40fe15cb3995e9333e4c3609..a0d88da6e9d03c10f26e9707be6e08494db3bfea 100644 --- a/ccsrc/Protocols/CAM_Layers/module.mk +++ b/ccsrc/Protocols/CAM_Layers/module.mk @@ -1,2 +1,2 @@ -sources := cam_layer.cc -includes := . ../CAM_Codecs +sources := cam_layer.cc +includes := . ../CAM_Codecs diff --git a/ccsrc/Protocols/Commsignia/commsignia_layer.cc b/ccsrc/Protocols/Commsignia/commsignia_layer.cc index 79e9fd09f8159f4a9a386a6aff5b98feba38658b..81fd55401aec1c610f6e1f0ae6b88345ab25a765 100644 --- a/ccsrc/Protocols/Commsignia/commsignia_layer.cc +++ b/ccsrc/Protocols/Commsignia/commsignia_layer.cc @@ -1,265 +1,265 @@ -#include -#include -#include - -#include "commsignia_layer_factory.hh" - -#include "loggers.hh" - -#include "converter.hh" - -unsigned char commsignia_layer::_g5_fixed_header[10] = {0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x0D}; - -commsignia_layer::commsignia_layer(const std::string &p_type, const std::string ¶m) : layer(p_type), _params(), _mac_src(), _eth_type() { - loggers::get_instance().log(">>> commsignia_layer::commsignia_layer: %s, %s", to_string().c_str(), param.c_str()); - - // Setup parameters - params::convert(_params, param); - params::const_iterator it = _params.find(params::mac_src); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("mac_src"), "000000000000")); - } - _mac_src = converter::get_instance().hexa_to_bytes(_params[params::mac_src]); - it = _params.find(params::mac_bc); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("mac_bc"), "FFFFFFFFFFFF")); - } - it = _params.find(params::eth_type); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("eth_type"), "8947")); - } - _eth_type = converter::get_instance().hexa_to_bytes(_params[params::eth_type]); - it = _params.find(params::interface_id); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("interface_id"), "1")); // The interfce id for filtering & to send on - } - it = _params.find(std::string("power_tx")); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("power_tx"), "20")); // 20db - } - it = _params.find(std::string("data_rate")); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("data_rate"), "12")); // 12 * 500Kbps = 6Mbps - } - it = _params.find(std::string("use_vpn")); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("use_vpn"), "0")); - } - it = _params.find(std::string("xport_mode")); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("xport_mode"), "G5")); - } - //_params.log(); -} - -void commsignia_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> commsignia_layer::send_data: ", data); - - OCTETSTRING buffer = OCTETSTRING(0, nullptr); - if (_params[std::string("xport_mode")].compare("G5") == 0) { - buffer = OCTETSTRING(10, commsignia_layer::_g5_fixed_header); - if (_params[std::string("use_vpn")].compare("1") == 0) { - buffer += int2oct(1, 1); // Injection to software - } else { - buffer += int2oct(0, 1); // Injection to radio - } - buffer += int2oct(0, 1); // Fix - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Injection=", buffer); - buffer += int2oct(std::stoi(_params[params::interface_id]), 4); - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Interface=", buffer); - buffer += int2oct(std::stoi(_params[std::string("data_rate")]), 2); - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: data_rate=", buffer); - buffer += int2oct(7, 1); // MAC user priority - buffer += int2oct(0x80000000 & std::stoi(_params[std::string("power_tx")]), 4); // Negative number - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: PowerTx=", buffer); - // Destination MAC address - params::const_iterator it = params.find(params::mac_dst); // Find in provided parameters, params - if (it != params.cend()) { - buffer += str2oct(CHARSTRING(it->second.c_str())); - } else { - it = _params.find(params::mac_dst); - if (it != _params.cend()) { - buffer += str2oct(CHARSTRING(it->second.c_str())); - } else { - buffer += str2oct(CHARSTRING(_params[params::mac_bc].c_str())); - } - } - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: mac_dst=", buffer); - // Source MAC address - it = params.find(params::mac_src); // Find in provided parameters, params - if (it != params.cend()) { - buffer += str2oct(CHARSTRING(it->second.c_str())); - } else { - it = _params.find(params::mac_src); - if (it != _params.cend()) { - buffer += str2oct(CHARSTRING(it->second.c_str())); - } else { - buffer += str2oct(CHARSTRING(_params[params::mac_src].c_str())); - } - } - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: mac_src=", buffer); - buffer += int2oct(0, 2); // Fixed - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Fixed=", buffer); - buffer += int2oct(data.lengthof(), 2); // Data length - loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Data length=", buffer); - } // else, LTE-V2X, injection buffer = GN+BTP+CAM/DENM only - buffer += data; // Payload - - loggers::get_instance().log_msg("commsignia_layer::send_data: Final buffer=", buffer); - send_to_all_layers(buffer, params); -} - -void commsignia_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> commsignia_layer::receive_data: ", data); - - const unsigned char *p = static_cast(data); - const unsigned char c2p_ver = (unsigned char)*p; - - // Check the frame version - if ((c2p_ver != 0x11) && (c2p_ver != 0x17)) { // Rx G5 or LTE-V2X - // Discard it, only use G5 or LTE-V2X RX version - return; - } - - if (c2p_ver == 0x11) { // G5 - commsignia_layer::c2p_s_v1_rx_t r; - r.s_header.u8_ver_type = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: version=%02x", r.s_header.u8_ver_type); - memcpy((void *)&r.s_header.u32_tst_sec, (unsigned int *)p, sizeof(unsigned int)); - p += sizeof(unsigned int); - loggers::get_instance().log("commsignia_layer::receive_data: time (in s)=%08x", /*ntohl(*/ r.s_header.u32_tst_sec) /*)*/; - memcpy((void *)&r.s_header.u32_tst_msec, (unsigned int *)p, sizeof(unsigned int)); - p += sizeof(unsigned int); - loggers::get_instance().log("commsignia_layer::receive_data: time (in ms)=%08x", /*ntohl(*/ r.s_header.u32_tst_msec) /*)*/; - r.u8_primary_channel = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: primary_channel=%02x", r.u8_primary_channel); - r.u8_secondary_channel = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: secondary_channel=%02x", r.u8_secondary_channel); - r.u8_used_interface = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: used_interface=%02x", r.u8_used_interface); - r.u8_data_rate = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: data_rate=%02x", r.u8_data_rate); - r.u8_antenna = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: antenna=%02x", r.u8_antenna); - memcpy((void *)&r.s32_latitude, (int *)p, sizeof(int)); - p += sizeof(int); - loggers::get_instance().log("commsignia_layer::receive_data: latitude=%08x", r.s32_latitude); - memcpy((void *)&r.s32_longitude, (int *)p, sizeof(int)); - p += sizeof(int); - loggers::get_instance().log("commsignia_layer::receive_data: longitude=%08x", r.s32_longitude); - memcpy((void *)&r.u16_speed, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: speed=%02x", r.u16_speed); // ntohs - memcpy((void *)&r.u16_heading, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: heading=%02x", r.u16_heading); - r.s8_rssi_ant_1 = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: s8_rssi_ant_1=%02x", r.s8_rssi_ant_1); - r.s8_rssi_ant_2 = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: s8_rssi_ant_2=%02x", r.s8_rssi_ant_2); - r.s8_noise_ant_1 = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: s8_noise_ant_1=%02x", r.s8_noise_ant_1); - r.s8_noise_ant_2 = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: s8_noise_ant_2=%02x", r.s8_noise_ant_2); - memcpy((void *)&r.u16_cbr_ant_1, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: cbr_ant_1=%04x", r.u16_cbr_ant_1); - memcpy((void *)&r.u16_cbr_ant_2, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: cbr_ant_2=%04x", r.u16_cbr_ant_2); - // Filtering on antenna index - loggers::get_instance().log("commsignia_layer::receive_data: compare %02x with %02x", r.u8_antenna, - static_cast(std::stoi(_params[params::interface_id]))); - if (r.u8_antenna != std::stoi(_params[params::interface_id])) { - // Discard packet - loggers::get_instance().warning("commsignia_layer::receive_data: Discard packet due to wrong antenna id"); - // TODO return; - } // else, continue - } else { // LTE-CV2X - commsignia_layer::c2p_s_v1_rx_cv2x_t r; - r.s_header.u8_ver_type = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: version=%02x", r.s_header.u8_ver_type); - memcpy((void *)&r.s_header.u32_tst_sec, (unsigned int *)p, sizeof(unsigned int)); - p += sizeof(unsigned int); - loggers::get_instance().log("commsignia_layer::receive_data: time (in s)=%08x", /*ntohl(*/ r.s_header.u32_tst_sec) /*)*/; - memcpy((void *)&r.s_header.u32_tst_msec, (unsigned int *)p, sizeof(unsigned int)); - p += sizeof(unsigned int); - loggers::get_instance().log("commsignia_layer::receive_data: time (in ms)=%08x", /*ntohl(*/ r.s_header.u32_tst_msec) /*)*/; - r.u8_socket_index = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: u8_socket_index=%02x", r.u8_socket_index); - memcpy((void *)&r.u16_ethertype, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: u16_ethertype=%04x", r.u16_ethertype); - r.s8_rssi = (signed char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: s8_rssi=%02x", r.s8_rssi); - r.u8_datarate_500kbps = (unsigned char)*p++; - loggers::get_instance().log("commsignia_layer::receive_data: u8_datarate_500kbps=%02x", r.u8_datarate_500kbps); - } - - commsignia_layer::c2p_802_11p_hdr h; - memcpy((void *)&h.frame_ctrl, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: frame_ctrl=%04x", h.frame_ctrl); - memcpy((void *)&h.duration, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: duration=%04x", h.duration); - memcpy((void *)&h.dst_addr, (unsigned short *)p, 6 * sizeof(unsigned char)); - p += 6 * sizeof(unsigned char); - memcpy((void *)&h.src_addr, (unsigned short *)p, 6 * sizeof(unsigned char)); - p += 6 * sizeof(unsigned char); - memcpy((void *)&h.bss_id, (unsigned short *)p, 6 * sizeof(unsigned char)); - p += 6 * sizeof(unsigned char); - memcpy((void *)&h.fragment_seq_num, (unsigned short *)p, sizeof(unsigned short)); - p += sizeof(unsigned short); - loggers::get_instance().log("commsignia_layer::receive_data: fragment_seq_num=%04x", h.fragment_seq_num); - - OCTETSTRING bid = OCTETSTRING(6, (const unsigned char *)&h.bss_id); // TODO To be removed - loggers::get_instance().log_msg("commsignia_layer::receive_data: bss_id: ", bid); - OCTETSTRING dst = OCTETSTRING(6, (const unsigned char *)&h.dst_addr); - loggers::get_instance().log_msg("commsignia_layer::receive_data: dst: ", dst); - OCTETSTRING src = OCTETSTRING(6, (const unsigned char *)&h.src_addr); - loggers::get_instance().log_msg("commsignia_layer::receive_data: src: ", src); - - // Filtering on source MAC address of the packet - if (!std::equal(_mac_src.cbegin(), _mac_src.cend(), static_cast(src))) { - // Discard packet - loggers::get_instance().warning("commsignia_layer::receive_data: Discard packet due to wrong comparison"); - // TODO return; - } // else, continue - int length; - if (c2p_ver == 0x11) { - const commsignia_layer::c2p_llc_hdr *l; - if ((ntohs(h.frame_ctrl) & 0xf000) == 0x8000) { - l = (const commsignia_layer::c2p_llc_hdr *)(static_cast(data) + sizeof(commsignia_layer::c2p_s_v1_rx_t) + - sizeof(commsignia_layer::c2p_802_11p_hdr) + sizeof(commsignia_layer::c2p_qos_ctrl)); - length = sizeof(commsignia_layer::c2p_s_v1_rx_t) + sizeof(commsignia_layer::c2p_802_11p_hdr) + sizeof(commsignia_layer::c2p_qos_ctrl) + - sizeof(commsignia_layer::c2p_llc_hdr); - } else { - l = (const commsignia_layer::c2p_llc_hdr *)(p + sizeof(commsignia_layer::c2p_s_v1_rx_t) + sizeof(commsignia_layer::c2p_802_11p_hdr)); - length = sizeof(commsignia_layer::c2p_s_v1_rx_t) + sizeof(commsignia_layer::c2p_802_11p_hdr) + sizeof(commsignia_layer::c2p_llc_hdr); - } - } else { // LTE-V2X - length = sizeof(commsignia_layer::c2p_s_v1_rx_cv2x_t) + sizeof(commsignia_layer::c2p_802_11p_hdr) + 10 /*Fixed size*/; - } - - // Check ether type - // if ((_eth_type[1] == (unsigned char)((l->type & 0xff00) >> 8)) && (_eth_type[0] == (unsigned char)(l->type & 0xff))) { // Warning: Network ordered bytes - // Extract payload - data = OCTETSTRING(data.lengthof() - length, length + static_cast(data)); - // loggers::get_instance().log_msg("commsignia_layer::receive_data: payload for upper layer:", data); - - // Update params - CHARSTRING s = oct2str(dst); - params[params::mac_dst] = std::string(static_cast(s)); - s = oct2str(src); - params[params::mac_src] = std::string(static_cast(s)); - - receive_to_all_layers(data, params); - /*} else { - // Discard packet - loggers::get_instance().warning("commsignia_layer::receive_data: Discard packet due to wrong ethernet type"); - //TODO return; - }*/ -} - -commsignia_layer_factory commsignia_layer_factory::_f; +#include +#include +#include + +#include "commsignia_layer_factory.hh" + +#include "loggers.hh" + +#include "converter.hh" + +unsigned char commsignia_layer::_g5_fixed_header[10] = {0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x0D}; + +commsignia_layer::commsignia_layer(const std::string &p_type, const std::string ¶m) : layer(p_type), _params(), _mac_src(), _eth_type() { + loggers::get_instance().log(">>> commsignia_layer::commsignia_layer: %s, %s", to_string().c_str(), param.c_str()); + + // Setup parameters + params::convert(_params, param); + params::const_iterator it = _params.find(params::mac_src); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("mac_src"), "000000000000")); + } + _mac_src = converter::get_instance().hexa_to_bytes(_params[params::mac_src]); + it = _params.find(params::mac_bc); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("mac_bc"), "FFFFFFFFFFFF")); + } + it = _params.find(params::eth_type); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("eth_type"), "8947")); + } + _eth_type = converter::get_instance().hexa_to_bytes(_params[params::eth_type]); + it = _params.find(params::interface_id); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("interface_id"), "1")); // The interfce id for filtering & to send on + } + it = _params.find(std::string("power_tx")); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("power_tx"), "20")); // 20db + } + it = _params.find(std::string("data_rate")); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("data_rate"), "12")); // 12 * 500Kbps = 6Mbps + } + it = _params.find(std::string("use_vpn")); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("use_vpn"), "0")); + } + it = _params.find(std::string("xport_mode")); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("xport_mode"), "G5")); + } + //_params.log(); +} + +void commsignia_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> commsignia_layer::send_data: ", data); + + OCTETSTRING buffer = OCTETSTRING(0, nullptr); + if (_params[std::string("xport_mode")].compare("G5") == 0) { + buffer = OCTETSTRING(10, commsignia_layer::_g5_fixed_header); + if (_params[std::string("use_vpn")].compare("1") == 0) { + buffer += int2oct(1, 1); // Injection to software + } else { + buffer += int2oct(0, 1); // Injection to radio + } + buffer += int2oct(0, 1); // Fix + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Injection=", buffer); + buffer += int2oct(std::stoi(_params[params::interface_id]), 4); + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Interface=", buffer); + buffer += int2oct(std::stoi(_params[std::string("data_rate")]), 2); + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: data_rate=", buffer); + buffer += int2oct(7, 1); // MAC user priority + buffer += int2oct(0x80000000 & std::stoi(_params[std::string("power_tx")]), 4); // Negative number + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: PowerTx=", buffer); + // Destination MAC address + params::const_iterator it = params.find(params::mac_dst); // Find in provided parameters, params + if (it != params.cend()) { + buffer += str2oct(CHARSTRING(it->second.c_str())); + } else { + it = _params.find(params::mac_dst); + if (it != _params.cend()) { + buffer += str2oct(CHARSTRING(it->second.c_str())); + } else { + buffer += str2oct(CHARSTRING(_params[params::mac_bc].c_str())); + } + } + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: mac_dst=", buffer); + // Source MAC address + it = params.find(params::mac_src); // Find in provided parameters, params + if (it != params.cend()) { + buffer += str2oct(CHARSTRING(it->second.c_str())); + } else { + it = _params.find(params::mac_src); + if (it != _params.cend()) { + buffer += str2oct(CHARSTRING(it->second.c_str())); + } else { + buffer += str2oct(CHARSTRING(_params[params::mac_src].c_str())); + } + } + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: mac_src=", buffer); + buffer += int2oct(0, 2); // Fixed + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Fixed=", buffer); + buffer += int2oct(data.lengthof(), 2); // Data length + loggers::get_instance().log_msg("commsignia_layer::send_data: buffer: Data length=", buffer); + } // else, LTE-V2X, injection buffer = GN+BTP+CAM/DENM only + buffer += data; // Payload + + loggers::get_instance().log_msg("commsignia_layer::send_data: Final buffer=", buffer); + send_to_all_layers(buffer, params); +} + +void commsignia_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> commsignia_layer::receive_data: ", data); + + const unsigned char *p = static_cast(data); + const unsigned char c2p_ver = (unsigned char)*p; + + // Check the frame version + if ((c2p_ver != 0x11) && (c2p_ver != 0x17)) { // Rx G5 or LTE-V2X + // Discard it, only use G5 or LTE-V2X RX version + return; + } + + if (c2p_ver == 0x11) { // G5 + commsignia_layer::c2p_s_v1_rx_t r; + r.s_header.u8_ver_type = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: version=%02x", r.s_header.u8_ver_type); + memcpy((void *)&r.s_header.u32_tst_sec, (unsigned int *)p, sizeof(unsigned int)); + p += sizeof(unsigned int); + loggers::get_instance().log("commsignia_layer::receive_data: time (in s)=%08x", /*ntohl(*/ r.s_header.u32_tst_sec) /*)*/; + memcpy((void *)&r.s_header.u32_tst_msec, (unsigned int *)p, sizeof(unsigned int)); + p += sizeof(unsigned int); + loggers::get_instance().log("commsignia_layer::receive_data: time (in ms)=%08x", /*ntohl(*/ r.s_header.u32_tst_msec) /*)*/; + r.u8_primary_channel = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: primary_channel=%02x", r.u8_primary_channel); + r.u8_secondary_channel = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: secondary_channel=%02x", r.u8_secondary_channel); + r.u8_used_interface = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: used_interface=%02x", r.u8_used_interface); + r.u8_data_rate = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: data_rate=%02x", r.u8_data_rate); + r.u8_antenna = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: antenna=%02x", r.u8_antenna); + memcpy((void *)&r.s32_latitude, (int *)p, sizeof(int)); + p += sizeof(int); + loggers::get_instance().log("commsignia_layer::receive_data: latitude=%08x", r.s32_latitude); + memcpy((void *)&r.s32_longitude, (int *)p, sizeof(int)); + p += sizeof(int); + loggers::get_instance().log("commsignia_layer::receive_data: longitude=%08x", r.s32_longitude); + memcpy((void *)&r.u16_speed, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: speed=%02x", r.u16_speed); // ntohs + memcpy((void *)&r.u16_heading, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: heading=%02x", r.u16_heading); + r.s8_rssi_ant_1 = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: s8_rssi_ant_1=%02x", r.s8_rssi_ant_1); + r.s8_rssi_ant_2 = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: s8_rssi_ant_2=%02x", r.s8_rssi_ant_2); + r.s8_noise_ant_1 = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: s8_noise_ant_1=%02x", r.s8_noise_ant_1); + r.s8_noise_ant_2 = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: s8_noise_ant_2=%02x", r.s8_noise_ant_2); + memcpy((void *)&r.u16_cbr_ant_1, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: cbr_ant_1=%04x", r.u16_cbr_ant_1); + memcpy((void *)&r.u16_cbr_ant_2, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: cbr_ant_2=%04x", r.u16_cbr_ant_2); + // Filtering on antenna index + loggers::get_instance().log("commsignia_layer::receive_data: compare %02x with %02x", r.u8_antenna, + static_cast(std::stoi(_params[params::interface_id]))); + if (r.u8_antenna != std::stoi(_params[params::interface_id])) { + // Discard packet + loggers::get_instance().warning("commsignia_layer::receive_data: Discard packet due to wrong antenna id"); + // TODO return; + } // else, continue + } else { // LTE-CV2X + commsignia_layer::c2p_s_v1_rx_cv2x_t r; + r.s_header.u8_ver_type = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: version=%02x", r.s_header.u8_ver_type); + memcpy((void *)&r.s_header.u32_tst_sec, (unsigned int *)p, sizeof(unsigned int)); + p += sizeof(unsigned int); + loggers::get_instance().log("commsignia_layer::receive_data: time (in s)=%08x", /*ntohl(*/ r.s_header.u32_tst_sec) /*)*/; + memcpy((void *)&r.s_header.u32_tst_msec, (unsigned int *)p, sizeof(unsigned int)); + p += sizeof(unsigned int); + loggers::get_instance().log("commsignia_layer::receive_data: time (in ms)=%08x", /*ntohl(*/ r.s_header.u32_tst_msec) /*)*/; + r.u8_socket_index = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: u8_socket_index=%02x", r.u8_socket_index); + memcpy((void *)&r.u16_ethertype, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: u16_ethertype=%04x", r.u16_ethertype); + r.s8_rssi = (signed char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: s8_rssi=%02x", r.s8_rssi); + r.u8_datarate_500kbps = (unsigned char)*p++; + loggers::get_instance().log("commsignia_layer::receive_data: u8_datarate_500kbps=%02x", r.u8_datarate_500kbps); + } + + commsignia_layer::c2p_802_11p_hdr h; + memcpy((void *)&h.frame_ctrl, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: frame_ctrl=%04x", h.frame_ctrl); + memcpy((void *)&h.duration, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: duration=%04x", h.duration); + memcpy((void *)&h.dst_addr, (unsigned short *)p, 6 * sizeof(unsigned char)); + p += 6 * sizeof(unsigned char); + memcpy((void *)&h.src_addr, (unsigned short *)p, 6 * sizeof(unsigned char)); + p += 6 * sizeof(unsigned char); + memcpy((void *)&h.bss_id, (unsigned short *)p, 6 * sizeof(unsigned char)); + p += 6 * sizeof(unsigned char); + memcpy((void *)&h.fragment_seq_num, (unsigned short *)p, sizeof(unsigned short)); + p += sizeof(unsigned short); + loggers::get_instance().log("commsignia_layer::receive_data: fragment_seq_num=%04x", h.fragment_seq_num); + + OCTETSTRING bid = OCTETSTRING(6, (const unsigned char *)&h.bss_id); // TODO To be removed + loggers::get_instance().log_msg("commsignia_layer::receive_data: bss_id: ", bid); + OCTETSTRING dst = OCTETSTRING(6, (const unsigned char *)&h.dst_addr); + loggers::get_instance().log_msg("commsignia_layer::receive_data: dst: ", dst); + OCTETSTRING src = OCTETSTRING(6, (const unsigned char *)&h.src_addr); + loggers::get_instance().log_msg("commsignia_layer::receive_data: src: ", src); + + // Filtering on source MAC address of the packet + if (!std::equal(_mac_src.cbegin(), _mac_src.cend(), static_cast(src))) { + // Discard packet + loggers::get_instance().warning("commsignia_layer::receive_data: Discard packet due to wrong comparison"); + // TODO return; + } // else, continue + int length; + if (c2p_ver == 0x11) { + const commsignia_layer::c2p_llc_hdr *l; + if ((ntohs(h.frame_ctrl) & 0xf000) == 0x8000) { + l = (const commsignia_layer::c2p_llc_hdr *)(static_cast(data) + sizeof(commsignia_layer::c2p_s_v1_rx_t) + + sizeof(commsignia_layer::c2p_802_11p_hdr) + sizeof(commsignia_layer::c2p_qos_ctrl)); + length = sizeof(commsignia_layer::c2p_s_v1_rx_t) + sizeof(commsignia_layer::c2p_802_11p_hdr) + sizeof(commsignia_layer::c2p_qos_ctrl) + + sizeof(commsignia_layer::c2p_llc_hdr); + } else { + l = (const commsignia_layer::c2p_llc_hdr *)(p + sizeof(commsignia_layer::c2p_s_v1_rx_t) + sizeof(commsignia_layer::c2p_802_11p_hdr)); + length = sizeof(commsignia_layer::c2p_s_v1_rx_t) + sizeof(commsignia_layer::c2p_802_11p_hdr) + sizeof(commsignia_layer::c2p_llc_hdr); + } + } else { // LTE-V2X + length = sizeof(commsignia_layer::c2p_s_v1_rx_cv2x_t) + sizeof(commsignia_layer::c2p_802_11p_hdr) + 10 /*Fixed size*/; + } + + // Check ether type + // if ((_eth_type[1] == (unsigned char)((l->type & 0xff00) >> 8)) && (_eth_type[0] == (unsigned char)(l->type & 0xff))) { // Warning: Network ordered bytes + // Extract payload + data = OCTETSTRING(data.lengthof() - length, length + static_cast(data)); + // loggers::get_instance().log_msg("commsignia_layer::receive_data: payload for upper layer:", data); + + // Update params + CHARSTRING s = oct2str(dst); + params[params::mac_dst] = std::string(static_cast(s)); + s = oct2str(src); + params[params::mac_src] = std::string(static_cast(s)); + + receive_to_all_layers(data, params); + /*} else { + // Discard packet + loggers::get_instance().warning("commsignia_layer::receive_data: Discard packet due to wrong ethernet type"); + //TODO return; + }*/ +} + +commsignia_layer_factory commsignia_layer_factory::_f; diff --git a/ccsrc/Protocols/Commsignia/commsignia_layer.hh b/ccsrc/Protocols/Commsignia/commsignia_layer.hh index 651df7b8244a129db745109f69f1d0bbcfc74be2..5b2d52d5cb892d463e515e2fcf418adef646d3dc 100644 --- a/ccsrc/Protocols/Commsignia/commsignia_layer.hh +++ b/ccsrc/Protocols/Commsignia/commsignia_layer.hh @@ -1,136 +1,136 @@ -/*! - * \file udp_layer_factory.hh - * \brief Header file for ITS Commsignia port protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "params.hh" -#include "t_layer.hh" - -class OCTETSTRING; //! Forward declaration of TITAN class - -/*! - * \class commsignia_layer - * \brief This class provides description of ITS Commsignia port protocol layer - */ -class commsignia_layer : public layer { - static constexpr unsigned char LL_ADDR_LENGTH = 6; - static constexpr unsigned char LL_ORG_CODE_LENGTH = 3; - - /** - * \struct C2P packet description - */ - typedef struct { - unsigned char u8_ver_type; - unsigned int u32_tst_sec; - unsigned int u32_tst_msec; - } __attribute__((__packed__)) c2p_s_header_t; - typedef struct { - c2p_s_header_t s_header; - unsigned char u8_primary_channel; - unsigned char u8_secondary_channel; - unsigned char u8_used_interface; - unsigned char u8_data_rate; - unsigned char u8_antenna; - int s32_latitude; - int s32_longitude; - unsigned short u16_speed; - unsigned short u16_heading; - signed char s8_rssi_ant_1; - signed char s8_rssi_ant_2; - signed char s8_noise_ant_1; - signed char s8_noise_ant_2; - unsigned short u16_cbr_ant_1; - unsigned short u16_cbr_ant_2; - } __attribute__((__packed__)) c2p_s_v1_rx_t; - typedef struct { - c2p_s_header_t s_header; - unsigned char u8_primary_channel; - unsigned char u8_secondary_channel; - unsigned char u8_used_interface; - unsigned char u8_data_rate; - unsigned char u8_antenna; - int s32_latitude; - int s32_longitude; - unsigned short u16_speed; - unsigned short u16_heading; - signed char s8_txp; - signed char s8_rssi_ant_1; - signed char s8_rssi_ant_2; - } __attribute__((__packed__)) c2p_s_v1_tx_t; - typedef struct { - c2p_s_header_t s_header; - unsigned char u8_socket_index; - unsigned short u16_ethertype; - signed char s8_rssi; - unsigned char u8_datarate_500kbps; - } __attribute__((__packed__)) c2p_s_v1_rx_cv2x_t; - typedef struct { - c2p_s_header_t s_header; - unsigned char u8_b_sps; - unsigned short u16_sps_port; - unsigned short u16_event_port; - int s32_tx_pwr_dbm; - int s32_bw_res_v2xid; - int s32_bw_res_period_interval_ms; - int s32_bw_res_tx_reservation_size_bytes; - unsigned char u8_bw_res_tx_priority; - } __attribute__((__packed__)) c2p_s_v1_tx_cv2x_t; - - /** - * \struct Injected data header - */ - typedef struct { - unsigned short frame_ctrl; - unsigned short duration; - unsigned char dst_addr[commsignia_layer::LL_ADDR_LENGTH]; - unsigned char src_addr[commsignia_layer::LL_ADDR_LENGTH]; - unsigned char bss_id[commsignia_layer::LL_ADDR_LENGTH]; - unsigned short fragment_seq_num; - } __attribute__((__packed__)) c2p_802_11p_hdr; - - typedef unsigned short c2p_qos_ctrl; - - /** - * \struct C2P/c2p_s_llc_hdr_t - */ - typedef struct { - unsigned char dsap; - unsigned char ssap; - unsigned char ctrl; - unsigned char org_code[commsignia_layer::LL_ORG_CODE_LENGTH]; - unsigned short type; - } __attribute__((__packed__)) c2p_llc_hdr; - - params _params; //! Layer parameters - std::vector _mac_src; //! Used to optimize filtering on source mac address in \see commsignia_layer::receive_data method - std::vector _eth_type; //! Used to optimize filtering on ethernet type in \see commsignia_layer::receive_data method - - //! Fixed header for packet injection - static unsigned char _g5_fixed_header[10]; - static unsigned char _cv2x_fixed_header[10]; - -public: - //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the commsignia_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - commsignia_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - * \remark If \see _reconnect_on_send is set to false, the disconnection is done by the destructor - */ - virtual ~commsignia_layer(){}; - - virtual void send_data(OCTETSTRING &data, params ¶ms); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class commsignia_layer +/*! + * \file udp_layer_factory.hh + * \brief Header file for ITS Commsignia port protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "params.hh" +#include "t_layer.hh" + +class OCTETSTRING; //! Forward declaration of TITAN class + +/*! + * \class commsignia_layer + * \brief This class provides description of ITS Commsignia port protocol layer + */ +class commsignia_layer : public layer { + static constexpr unsigned char LL_ADDR_LENGTH = 6; + static constexpr unsigned char LL_ORG_CODE_LENGTH = 3; + + /** + * \struct C2P packet description + */ + typedef struct { + unsigned char u8_ver_type; + unsigned int u32_tst_sec; + unsigned int u32_tst_msec; + } __attribute__((__packed__)) c2p_s_header_t; + typedef struct { + c2p_s_header_t s_header; + unsigned char u8_primary_channel; + unsigned char u8_secondary_channel; + unsigned char u8_used_interface; + unsigned char u8_data_rate; + unsigned char u8_antenna; + int s32_latitude; + int s32_longitude; + unsigned short u16_speed; + unsigned short u16_heading; + signed char s8_rssi_ant_1; + signed char s8_rssi_ant_2; + signed char s8_noise_ant_1; + signed char s8_noise_ant_2; + unsigned short u16_cbr_ant_1; + unsigned short u16_cbr_ant_2; + } __attribute__((__packed__)) c2p_s_v1_rx_t; + typedef struct { + c2p_s_header_t s_header; + unsigned char u8_primary_channel; + unsigned char u8_secondary_channel; + unsigned char u8_used_interface; + unsigned char u8_data_rate; + unsigned char u8_antenna; + int s32_latitude; + int s32_longitude; + unsigned short u16_speed; + unsigned short u16_heading; + signed char s8_txp; + signed char s8_rssi_ant_1; + signed char s8_rssi_ant_2; + } __attribute__((__packed__)) c2p_s_v1_tx_t; + typedef struct { + c2p_s_header_t s_header; + unsigned char u8_socket_index; + unsigned short u16_ethertype; + signed char s8_rssi; + unsigned char u8_datarate_500kbps; + } __attribute__((__packed__)) c2p_s_v1_rx_cv2x_t; + typedef struct { + c2p_s_header_t s_header; + unsigned char u8_b_sps; + unsigned short u16_sps_port; + unsigned short u16_event_port; + int s32_tx_pwr_dbm; + int s32_bw_res_v2xid; + int s32_bw_res_period_interval_ms; + int s32_bw_res_tx_reservation_size_bytes; + unsigned char u8_bw_res_tx_priority; + } __attribute__((__packed__)) c2p_s_v1_tx_cv2x_t; + + /** + * \struct Injected data header + */ + typedef struct { + unsigned short frame_ctrl; + unsigned short duration; + unsigned char dst_addr[commsignia_layer::LL_ADDR_LENGTH]; + unsigned char src_addr[commsignia_layer::LL_ADDR_LENGTH]; + unsigned char bss_id[commsignia_layer::LL_ADDR_LENGTH]; + unsigned short fragment_seq_num; + } __attribute__((__packed__)) c2p_802_11p_hdr; + + typedef unsigned short c2p_qos_ctrl; + + /** + * \struct C2P/c2p_s_llc_hdr_t + */ + typedef struct { + unsigned char dsap; + unsigned char ssap; + unsigned char ctrl; + unsigned char org_code[commsignia_layer::LL_ORG_CODE_LENGTH]; + unsigned short type; + } __attribute__((__packed__)) c2p_llc_hdr; + + params _params; //! Layer parameters + std::vector _mac_src; //! Used to optimize filtering on source mac address in \see commsignia_layer::receive_data method + std::vector _eth_type; //! Used to optimize filtering on ethernet type in \see commsignia_layer::receive_data method + + //! Fixed header for packet injection + static unsigned char _g5_fixed_header[10]; + static unsigned char _cv2x_fixed_header[10]; + +public: + //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the commsignia_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + commsignia_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + * \remark If \see _reconnect_on_send is set to false, the disconnection is done by the destructor + */ + virtual ~commsignia_layer(){}; + + virtual void send_data(OCTETSTRING &data, params ¶ms); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class commsignia_layer diff --git a/ccsrc/Protocols/Commsignia/commsignia_layer_factory.hh b/ccsrc/Protocols/Commsignia/commsignia_layer_factory.hh index b00453d8c3ae63bc3b65ed3b8f1d03ecca28a49a..f788899be9d4e085537ff23cc2e909b66014c6f6 100644 --- a/ccsrc/Protocols/Commsignia/commsignia_layer_factory.hh +++ b/ccsrc/Protocols/Commsignia/commsignia_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file commsignia_layer_factory.hh - * \brief Header file for ITS Commsignia protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "commsignia_layer.hh" - -/*! - * \class commsignia_layer_factory - * \brief This class provides a factory class to create an commsignia_layer class instance - */ -class commsignia_layer_factory : public layer_factory { - static commsignia_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the udp_layer_factory class - * \remark The Commsignia layer identifier is COMMSIGNIA - */ - commsignia_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("COMMSIGNIA", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new commsignia_layer(p_type, p_param); }; -}; // End of class commsignia_layer_factory +/*! + * \file commsignia_layer_factory.hh + * \brief Header file for ITS Commsignia protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "commsignia_layer.hh" + +/*! + * \class commsignia_layer_factory + * \brief This class provides a factory class to create an commsignia_layer class instance + */ +class commsignia_layer_factory : public layer_factory { + static commsignia_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the udp_layer_factory class + * \remark The Commsignia layer identifier is COMMSIGNIA + */ + commsignia_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("COMMSIGNIA", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new commsignia_layer(p_type, p_param); }; +}; // End of class commsignia_layer_factory diff --git a/ccsrc/Protocols/Commsignia/module.mk b/ccsrc/Protocols/Commsignia/module.mk index 2aa25d8e524d3f8a5acdb746015f91b0c2fb8e34..3d30cde03136a2abc8ec9e0fa38f638f06386b1e 100644 --- a/ccsrc/Protocols/Commsignia/module.mk +++ b/ccsrc/Protocols/Commsignia/module.mk @@ -1,3 +1,3 @@ -sources := commsignia_layer.cc -includes := . - +sources := commsignia_layer.cc +includes := . + diff --git a/ccsrc/Protocols/DENM/denm_codec.cc b/ccsrc/Protocols/DENM/denm_codec.cc index bc4fd592acefffaafed6b43242aae210de37f9e2..3349ff2af3c1dc120eee2a08e2658e128c7c4cbb 100644 --- a/ccsrc/Protocols/DENM/denm_codec.cc +++ b/ccsrc/Protocols/DENM/denm_codec.cc @@ -1,27 +1,27 @@ -#include "denm_codec.hh" -#include "LibItsDenm_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int denm_codec::encode(const DENM__PDU__Descriptions::DENM &p_denm, OCTETSTRING &p_data) { - loggers::get_instance().log_msg(">>> denm_codec::encode: ", p_denm); - - BITSTRING b; - int rc = asn_codec.encode(p_denm, b); - if (rc) { - p_data = bit2oct(b); - } - loggers::get_instance().log("<<< denm_codec::encode: %d", rc); - return rc; -} - -int denm_codec::decode(const OCTETSTRING &p_data, DENM__PDU__Descriptions::DENM &p_denm, params *params) { - loggers::get_instance().log_msg(">>> denm_codec::decode:", p_data); - - int rc = asn_codec.decode(oct2bit(p_data), p_denm); - loggers::get_instance().log("denm_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("denm_codec::decode: ", p_denm); - } - return rc; -} +#include "denm_codec.hh" +#include "LibItsDenm_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int denm_codec::encode(const DENM__PDU__Descriptions::DENM &p_denm, OCTETSTRING &p_data) { + loggers::get_instance().log_msg(">>> denm_codec::encode: ", p_denm); + + BITSTRING b; + int rc = asn_codec.encode(p_denm, b); + if (rc) { + p_data = bit2oct(b); + } + loggers::get_instance().log("<<< denm_codec::encode: %d", rc); + return rc; +} + +int denm_codec::decode(const OCTETSTRING &p_data, DENM__PDU__Descriptions::DENM &p_denm, params *params) { + loggers::get_instance().log_msg(">>> denm_codec::decode:", p_data); + + int rc = asn_codec.decode(oct2bit(p_data), p_denm); + loggers::get_instance().log("denm_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("denm_codec::decode: ", p_denm); + } + return rc; +} diff --git a/ccsrc/Protocols/DENM/denm_codec.hh b/ccsrc/Protocols/DENM/denm_codec.hh index 4242b243fc5a7bc9535be07249c1c82a82cd75d8..959067494611d0c654a430fb5a9149c881f6a786 100644 --- a/ccsrc/Protocols/DENM/denm_codec.hh +++ b/ccsrc/Protocols/DENM/denm_codec.hh @@ -1,26 +1,26 @@ -#pragma once - -#include "codec.hh" -#include "denm_pdu_codec.hh" -#include "params.hh" - -class BITSTRING; -class OCTETSTRING; -class Base_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace DENM__PDU__Descriptions { - class DENM; -} - -class denm_codec : public codec { - denm_pdu_codec asn_codec; - -public: - explicit denm_codec() : codec(), asn_codec(){}; - virtual ~denm_codec(){}; - - virtual int encode(const DENM__PDU__Descriptions::DENM &denm, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, DENM__PDU__Descriptions::DENM &, params *params = NULL); -}; +#pragma once + +#include "codec.hh" +#include "denm_pdu_codec.hh" +#include "params.hh" + +class BITSTRING; +class OCTETSTRING; +class Base_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace DENM__PDU__Descriptions { + class DENM; +} + +class denm_codec : public codec { + denm_pdu_codec asn_codec; + +public: + explicit denm_codec() : codec(), asn_codec(){}; + virtual ~denm_codec(){}; + + virtual int encode(const DENM__PDU__Descriptions::DENM &denm, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, DENM__PDU__Descriptions::DENM &, params *params = NULL); +}; diff --git a/ccsrc/Protocols/DENM/denm_layer.cc b/ccsrc/Protocols/DENM/denm_layer.cc index 62003889c8c3177718bc2efe1b06aec7f6d8651b..56f654453985966651a769333ad591e69da7e22c 100644 --- a/ccsrc/Protocols/DENM/denm_layer.cc +++ b/ccsrc/Protocols/DENM/denm_layer.cc @@ -1,147 +1,147 @@ -#include "denm_types.hh" - -#include "denm_layer_factory.hh" - -#include "registration.hh" - -#include "loggers.hh" - -denm_layer::denm_layer(const std::string &p_type, const std::string ¶m) : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> denm_layer::denm_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - _params.insert(std::make_pair("its_aid", "37")); // ETSI TS 102 965 V1.2.1 (2015-06) - _params.insert(std::make_pair("payload_type", "1")); // DE message id - See ETSI TS 102 894 - - // Register this object for AdapterControlPort - loggers::get_instance().log("denm_layer::denm_layer: Register %s/%p", p_type.c_str(), this); - registration::get_instance().add_item(p_type, this); -} - -void denm_layer::sendMsg(const LibItsDenm__TestSystem::DenmReq &p, params ¶ms) { - loggers::get_instance().log_msg(">>> denm_layer::sendMsg: ", p); - - // Encode DENM PDU - OCTETSTRING data; - if (_codec.encode(p.msgOut(), data) == -1) { - loggers::get_instance().warning("denm_layer::sendMsg: Encoding failure"); - return; - } - - send_data(data, _params); -} - -void denm_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> denm_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, params); -} - -void denm_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> denm_layer::receive_data: ", data); - - // Sanity check - if (*(static_cast(data) + 1) != 0x01) { // Check that received packet has DEN message id - See ETSI TS 102 894 - // Not a DENM message, discard it - loggers::get_instance().warning("denm_layer::receive_data: Wrong message id: 0x%02x", *(static_cast(data) + 1)); - return; - } - - // Decode the payload - LibItsDenm__TestSystem::DenmInd p; - _codec.decode(data, p.msgIn()); - if (!p.msgIn().is_bound()) { - // Discard it - return; - } // else, continue - - // Process lower layer data - // recvTime - params::const_iterator it = params.find(params::timestamp); - if (it != params.cend()) { - p.recvTime().set_long_long_val(std::stoll(it->second)); - } else { - p.recvTime().set_to_omit(); - } - // gnNextHeader - it = params.find(params::gn_next_header); - if (it != params.cend()) { - p.gnNextHeader() = std::stoi(it->second); - } else { - p.gnNextHeader().set_to_omit(); - } - // gnHeaderType - it = params.find(params::gn_header_type); - if (it != params.cend()) { - p.gnHeaderType() = std::stoi(it->second); - } else { - p.gnHeaderType().set_to_omit(); - } - // gnHeaderSubtype - it = params.find(params::gn_header_sub_type); - if (it != params.cend()) { - p.gnHeaderSubtype() = std::stoi(it->second); - } else { - p.gnHeaderSubtype().set_to_omit(); - } - // gnLifetime - it = params.find(params::gn_lifetime); - if (it != params.cend()) { - p.gnLifetime() = std::stoi(it->second); - } else { - p.gnLifetime().set_to_omit(); - } - // gnTrafficClass - it = params.find(params::gn_traffic_class); - if (it != params.cend()) { - p.gnTrafficClass() = std::stoi(it->second); - } else { - p.gnTrafficClass().set_to_omit(); - } - // btpDestinationPort - it = params.find(params::btp_destination_port); - if (it != params.cend()) { - p.btpDestinationPort() = std::stoi(it->second); - } else { - p.btpDestinationPort().set_to_omit(); - } - // btpInfo - it = params.find(params::btp_info); - if (it != params.cend()) { - p.btpInfo() = std::stoi(it->second); - } else { - p.btpInfo().set_to_omit(); - } - // ssp - it = params.find(params::ssp); - if (it != params.cend()) { - loggers::get_instance().log("denm_layer::receive_data: ssp=%s", it->second.c_str()); - p.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); - } else { - p.ssp().set_to_omit(); - } - // its_aid - it = params.find(params::its_aid); - if (it != params.cend()) { - p.its__aid() = std::stoi(it->second); - } else { - p.its__aid().set_to_omit(); - } - - // Pass it to the ports if any - to_all_upper_ports(p, params); -} - -int denm_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { - loggers::get_instance().log(">>> denm_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); - - return 0; -} - -int denm_layer::disable_secured_mode() { - loggers::get_instance().log(">>> denm_layer::disable_secured_mode"); - - return 0; -} - -denm_layer_factory denm_layer_factory::_f; +#include "denm_types.hh" + +#include "denm_layer_factory.hh" + +#include "registration.hh" + +#include "loggers.hh" + +denm_layer::denm_layer(const std::string &p_type, const std::string ¶m) : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> denm_layer::denm_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + _params.insert(std::make_pair("its_aid", "37")); // ETSI TS 102 965 V1.2.1 (2015-06) + _params.insert(std::make_pair("payload_type", "1")); // DE message id - See ETSI TS 102 894 + + // Register this object for AdapterControlPort + loggers::get_instance().log("denm_layer::denm_layer: Register %s/%p", p_type.c_str(), this); + registration::get_instance().add_item(p_type, this); +} + +void denm_layer::sendMsg(const LibItsDenm__TypesAndValues::DenmReq &p, params ¶ms) { + loggers::get_instance().log_msg(">>> denm_layer::sendMsg: ", p); + + // Encode DENM PDU + OCTETSTRING data; + if (_codec.encode(p.msgOut(), data) == -1) { + loggers::get_instance().warning("denm_layer::sendMsg: Encoding failure"); + return; + } + + send_data(data, _params); +} + +void denm_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> denm_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, params); +} + +void denm_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> denm_layer::receive_data: ", data); + + // Sanity check + if (*(static_cast(data) + 1) != 0x01) { // Check that received packet has DEN message id - See ETSI TS 102 894 + // Not a DENM message, discard it + loggers::get_instance().warning("denm_layer::receive_data: Wrong message id: 0x%02x", *(static_cast(data) + 1)); + return; + } + + // Decode the payload + LibItsDenm__TypesAndValues::DenmInd p; + _codec.decode(data, p.msgIn()); + if (!p.msgIn().is_bound()) { + // Discard it + return; + } // else, continue + + // Process lower layer data + // recvTime + params::const_iterator it = params.find(params::timestamp); + if (it != params.cend()) { + p.recvTime().set_long_long_val(std::stoll(it->second)); + } else { + p.recvTime().set_to_omit(); + } + // gnNextHeader + it = params.find(params::gn_next_header); + if (it != params.cend()) { + p.gnNextHeader() = std::stoi(it->second); + } else { + p.gnNextHeader().set_to_omit(); + } + // gnHeaderType + it = params.find(params::gn_header_type); + if (it != params.cend()) { + p.gnHeaderType() = std::stoi(it->second); + } else { + p.gnHeaderType().set_to_omit(); + } + // gnHeaderSubtype + it = params.find(params::gn_header_sub_type); + if (it != params.cend()) { + p.gnHeaderSubtype() = std::stoi(it->second); + } else { + p.gnHeaderSubtype().set_to_omit(); + } + // gnLifetime + it = params.find(params::gn_lifetime); + if (it != params.cend()) { + p.gnLifetime() = std::stoi(it->second); + } else { + p.gnLifetime().set_to_omit(); + } + // gnTrafficClass + it = params.find(params::gn_traffic_class); + if (it != params.cend()) { + p.gnTrafficClass() = std::stoi(it->second); + } else { + p.gnTrafficClass().set_to_omit(); + } + // btpDestinationPort + it = params.find(params::btp_destination_port); + if (it != params.cend()) { + p.btpDestinationPort() = std::stoi(it->second); + } else { + p.btpDestinationPort().set_to_omit(); + } + // btpInfo + it = params.find(params::btp_info); + if (it != params.cend()) { + p.btpInfo() = std::stoi(it->second); + } else { + p.btpInfo().set_to_omit(); + } + // ssp + it = params.find(params::ssp); + if (it != params.cend()) { + loggers::get_instance().log("denm_layer::receive_data: ssp=%s", it->second.c_str()); + p.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); + } else { + p.ssp().set_to_omit(); + } + // its_aid + it = params.find(params::its_aid); + if (it != params.cend()) { + p.its__aid() = std::stoi(it->second); + } else { + p.its__aid().set_to_omit(); + } + + // Pass it to the ports if any + to_all_upper_ports(p, params); +} + +int denm_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { + loggers::get_instance().log(">>> denm_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); + + return 0; +} + +int denm_layer::disable_secured_mode() { + loggers::get_instance().log(">>> denm_layer::disable_secured_mode"); + + return 0; +} + +denm_layer_factory denm_layer_factory::_f; diff --git a/ccsrc/Protocols/DENM/denm_layer.hh b/ccsrc/Protocols/DENM/denm_layer.hh index dbddaba912cab577131be69bb0368265a3ca0639..8997e673548034cc20c4477294d1c1b2262cdf45 100644 --- a/ccsrc/Protocols/DENM/denm_layer.hh +++ b/ccsrc/Protocols/DENM/denm_layer.hh @@ -1,76 +1,76 @@ -/*! - * \file denm_layer.hh - * \brief Header file for ITS DENM protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "denm_codec.hh" -#include "t_layer.hh" - -namespace LibItsDenm__TestSystem { - class DenmPort; //! Forward declaration of TITAN class - class DenmReq; //! Forward declaration of TITAN class - class DenmInd; //! Forward declaration of TITAN class -} // namespace LibItsDenm__TestSystem - -/*! - * \class denm_layer - * \brief This class provides description of ITS DENM protocol layer - */ -class denm_layer : public t_layer { - params _params; //! Layer parameters - denm_codec _codec; //! DENM codec -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the denm_layer class - */ - explicit denm_layer() : t_layer(), _params(), _codec(){}; - /*! - * \brief Specialised constructor - * Create a new instance of the denm_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - denm_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~denm_layer(){}; - - /*! - * \fn void sendMsg(const LibItsDenm__TestSystem::DenmReq& p_denm_req, params& p_params); - * \brief Send DEN message to the lower layers - * \param[in] p_denm_req The DEN message to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - void sendMsg(const LibItsDenm__TestSystem::DenmReq &p_denm_req, params ¶ms); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security); - - int disable_secured_mode(); - -}; // End of class denm_layer +/*! + * \file denm_layer.hh + * \brief Header file for ITS DENM protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "denm_codec.hh" +#include "t_layer.hh" + +namespace LibItsDenm__TestSystem { + class DenmPort; //! Forward declaration of TITAN class + class DenmReq; //! Forward declaration of TITAN class + class DenmInd; //! Forward declaration of TITAN class +} // namespace LibItsDenm__TestSystem + +/*! + * \class denm_layer + * \brief This class provides description of ITS DENM protocol layer + */ +class denm_layer : public t_layer { + params _params; //! Layer parameters + denm_codec _codec; //! DENM codec +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the denm_layer class + */ + explicit denm_layer() : t_layer(), _params(), _codec(){}; + /*! + * \brief Specialised constructor + * Create a new instance of the denm_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + denm_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~denm_layer(){}; + + /*! + * \fn void sendMsg(const LibItsDenm__TestSystem::DenmReq& p_denm_req, params& p_params); + * \brief Send DEN message to the lower layers + * \param[in] p_denm_req The DEN message to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + void sendMsg(const LibItsDenm__TypesAndValues::DenmReq &p_denm_req, params ¶ms); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security); + + int disable_secured_mode(); + +}; // End of class denm_layer diff --git a/ccsrc/Protocols/DENM/denm_layer_factory.hh b/ccsrc/Protocols/DENM/denm_layer_factory.hh index b309836da038f8b3547ea43910cb59395b1a00f3..e60b981677f5086d957facdc25563b62a8cd104c 100644 --- a/ccsrc/Protocols/DENM/denm_layer_factory.hh +++ b/ccsrc/Protocols/DENM/denm_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file denm_layer_factory.hh - * \brief Header file for ITS DENM protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "denm_layer.hh" - -/*! - * \class udp_layer_factory - * \brief This class provides a factory class to create an denm_layer class instance - */ -class denm_layer_factory : public layer_factory { - static denm_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the denm_layer_factory class - * \remark The DENM layer identifier is DENM - */ - denm_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("DENM", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new denm_layer(p_type, p_param); }; -}; // End of class denm_layer_factory +/*! + * \file denm_layer_factory.hh + * \brief Header file for ITS DENM protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "denm_layer.hh" + +/*! + * \class udp_layer_factory + * \brief This class provides a factory class to create an denm_layer class instance + */ +class denm_layer_factory : public layer_factory { + static denm_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the denm_layer_factory class + * \remark The DENM layer identifier is DENM + */ + denm_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("DENM", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new denm_layer(p_type, p_param); }; +}; // End of class denm_layer_factory diff --git a/ccsrc/Protocols/DENM/denm_pdu_codec.cc b/ccsrc/Protocols/DENM/denm_pdu_codec.cc index 935d2965c77bdf1bb07017dada10a8c7b3e3a684..e4e755a5dc996562a764152c8750c1b9a0826cf4 100644 --- a/ccsrc/Protocols/DENM/denm_pdu_codec.cc +++ b/ccsrc/Protocols/DENM/denm_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "denm_pdu_codec.hh" -#include "LibItsDenm_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_DENM; -} - -int denm_pdu_codec::encode(const DENM__PDU__Descriptions::DENM &p_denm, BITSTRING &p_data) { - return _encode(DENM__PDU__Descriptions::DENM_descr_, asn_DEF_DENM, p_denm, p_data); -} - -int denm_pdu_codec::decode(const BITSTRING &p_data, DENM__PDU__Descriptions::DENM &p_denm) { - return _decode(DENM__PDU__Descriptions::DENM_descr_, asn_DEF_DENM, p_data, p_denm); -} +#include "denm_pdu_codec.hh" +#include "LibItsDenm_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_DENM; +} + +int denm_pdu_codec::encode(const DENM__PDU__Descriptions::DENM &p_denm, BITSTRING &p_data) { + return _encode(DENM__PDU__Descriptions::DENM_descr_, asn_DEF_DENM, p_denm, p_data); +} + +int denm_pdu_codec::decode(const BITSTRING &p_data, DENM__PDU__Descriptions::DENM &p_denm) { + return _decode(DENM__PDU__Descriptions::DENM_descr_, asn_DEF_DENM, p_data, p_denm); +} diff --git a/ccsrc/Protocols/DENM/denm_pdu_codec.hh b/ccsrc/Protocols/DENM/denm_pdu_codec.hh index 32c0539f3b3fc567e3f0e86b813d8f9eb737a354..08bd0af14c288c5f71d5fdba8d88596e7cced21c 100644 --- a/ccsrc/Protocols/DENM/denm_pdu_codec.hh +++ b/ccsrc/Protocols/DENM/denm_pdu_codec.hh @@ -1,22 +1,22 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -class BITSTRING; -class OCTETSTRING; -class Base_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace DENM__PDU__Descriptions { - class DENM; -} - -class denm_pdu_codec : public per_codec { -public: - explicit denm_pdu_codec(){}; - virtual int encode(const DENM__PDU__Descriptions::DENM &denm, BITSTRING &data); - virtual int decode(const BITSTRING &data, DENM__PDU__Descriptions::DENM &); -}; +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +class BITSTRING; +class OCTETSTRING; +class Base_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace DENM__PDU__Descriptions { + class DENM; +} + +class denm_pdu_codec : public per_codec { +public: + explicit denm_pdu_codec(){}; + virtual int encode(const DENM__PDU__Descriptions::DENM &denm, BITSTRING &data); + virtual int decode(const BITSTRING &data, DENM__PDU__Descriptions::DENM &); +}; diff --git a/ccsrc/Protocols/DENM/denm_types.hh b/ccsrc/Protocols/DENM/denm_types.hh index bb2f25f5f96ef7b08f1dff8fa6db0d0dbcb5674e..c5e65f9aba139ab4a912d13051fef67438e9ce0c 100644 --- a/ccsrc/Protocols/DENM/denm_types.hh +++ b/ccsrc/Protocols/DENM/denm_types.hh @@ -1,15 +1,15 @@ -/*! - * \file denm_types.hh - * \brief Header file for TITAN DENM types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsDenm_TestSystem.hh" -#include "LibItsDenm_TypesAndValues.hh" +/*! + * \file denm_types.hh + * \brief Header file for TITAN DENM types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsDenm_TestSystem.hh" +#include "LibItsDenm_TypesAndValues.hh" diff --git a/ccsrc/Protocols/DENM/module.mk b/ccsrc/Protocols/DENM/module.mk index b33d283ff2ef7f93c8b330045d91f76ecb37c1b5..10cccb0b5f4e3bcf5ca10c40305a8301ad9c18d9 100644 --- a/ccsrc/Protocols/DENM/module.mk +++ b/ccsrc/Protocols/DENM/module.mk @@ -1,4 +1,4 @@ -sources := denm_codec.cc denm_layer.cc denm_pdu_codec.cc - -includes := . - +sources := denm_codec.cc denm_layer.cc denm_pdu_codec.cc + +includes := . + diff --git a/ccsrc/Protocols/ETH/ethernet_layer.cc b/ccsrc/Protocols/ETH/ethernet_layer.cc index d0ba32a00d25430551fe16cabda9ae914381a34a..f4004de55530668d88ff6b08066675f780559175 100644 --- a/ccsrc/Protocols/ETH/ethernet_layer.cc +++ b/ccsrc/Protocols/ETH/ethernet_layer.cc @@ -1,82 +1,82 @@ -#include "ethernet_layer_factory.hh" - -#include "loggers.hh" - -ethernet_layer::ethernet_layer(const std::string & p_type, const std::string & param) : layer(p_type), _params() { - loggers::get_instance().log(">>> ethernet_layer::ethernet_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - params::const_iterator it = _params.find("mac_src"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("mac_src"), "000000000000")); - } - it = _params.find("mac_bc"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("mac_bc"), "FFFFFFFFFFFF")); - } - it = _params.find("eth_type"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("eth_type"), "8947")); - } - //_params.log(); -} - -void ethernet_layer::send_data(OCTETSTRING& data, params& params) { - loggers::get_instance().log_msg(">>> ethernet_layer::send_data: ", data); - - OCTETSTRING eth; - // Destination MAC address - params::const_iterator it = params.find(params::mac_dst); // Find in provided parameters, params - if (it != params.cend()) { - eth = str2oct(CHARSTRING(it->second.c_str())); - } else { - it = _params.find(params::mac_dst); - if (it != _params.cend()) { - eth = str2oct(CHARSTRING(it->second.c_str())); - } else { - eth = str2oct(CHARSTRING(_params[params::mac_bc].c_str())); - } - } - // Source MAC address - it = params.find(params::mac_src); // Find in provided parameters, params - if (it != params.cend()) { - eth += str2oct(CHARSTRING(it->second.c_str())); - } else { - eth += str2oct(CHARSTRING(_params[params::mac_src].c_str())); - } - // Ethernet type - it = params.find(params::eth_type); // Find in layer parameters - if (it != params.cend()) { - eth += str2oct(CHARSTRING(it->second.c_str())); - } else { - eth += str2oct(CHARSTRING(_params[params::eth_type].c_str())); - } - - eth += data; - send_to_all_layers(eth, params); -} - -void ethernet_layer::receive_data(OCTETSTRING& data, params& params) { - loggers::get_instance().log_msg(">>> ethernet_layer::receive_data: ", data); - - // Extract dest MAC Address - OCTETSTRING dst = OCTETSTRING(6, static_cast(data)); - //loggers::get_instance().log_msg("ethernet_layer::receive_data: dst: ", dst); - // Extract source MAC Address - OCTETSTRING src = OCTETSTRING(6, 6 + static_cast(data)); - //loggers::get_instance().log_msg("ethernet_layer::receive_data: src: ", src); - // Extract ethertype - OCTETSTRING proto = OCTETSTRING(2, 2 + static_cast(data)); - //loggers::get_instance().log_msg("ethernet_layer::receive_data: proto: ", proto); - data = OCTETSTRING(data.lengthof() - 14, 14 + static_cast(data)); - // Update params - CHARSTRING s = oct2str(dst); - params.insert(std::pair(params::mac_dst, std::string(static_cast(s)))); - s = oct2str(src); - params.insert(std::pair(params::mac_src, std::string(static_cast(s)))); - //loggers::get_instance().log_msg("ethernet_layer::receive_data: payload for upper layer:", data); - - receive_to_all_layers(data, params); -} - -ethernet_layer_factory ethernet_layer_factory::_f; +#include "ethernet_layer_factory.hh" + +#include "loggers.hh" + +ethernet_layer::ethernet_layer(const std::string & p_type, const std::string & param) : layer(p_type), _params() { + loggers::get_instance().log(">>> ethernet_layer::ethernet_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + params::const_iterator it = _params.find("mac_src"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("mac_src"), "000000000000")); + } + it = _params.find("mac_bc"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("mac_bc"), "FFFFFFFFFFFF")); + } + it = _params.find("eth_type"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("eth_type"), "8947")); + } + //_params.log(); +} + +void ethernet_layer::send_data(OCTETSTRING& data, params& params) { + loggers::get_instance().log_msg(">>> ethernet_layer::send_data: ", data); + + OCTETSTRING eth; + // Destination MAC address + params::const_iterator it = params.find(params::mac_dst); // Find in provided parameters, params + if (it != params.cend()) { + eth = str2oct(CHARSTRING(it->second.c_str())); + } else { + it = _params.find(params::mac_dst); + if (it != _params.cend()) { + eth = str2oct(CHARSTRING(it->second.c_str())); + } else { + eth = str2oct(CHARSTRING(_params[params::mac_bc].c_str())); + } + } + // Source MAC address + it = params.find(params::mac_src); // Find in provided parameters, params + if (it != params.cend()) { + eth += str2oct(CHARSTRING(it->second.c_str())); + } else { + eth += str2oct(CHARSTRING(_params[params::mac_src].c_str())); + } + // Ethernet type + it = params.find(params::eth_type); // Find in layer parameters + if (it != params.cend()) { + eth += str2oct(CHARSTRING(it->second.c_str())); + } else { + eth += str2oct(CHARSTRING(_params[params::eth_type].c_str())); + } + + eth += data; + send_to_all_layers(eth, params); +} + +void ethernet_layer::receive_data(OCTETSTRING& data, params& params) { + loggers::get_instance().log_msg(">>> ethernet_layer::receive_data: ", data); + + // Extract dest MAC Address + OCTETSTRING dst = OCTETSTRING(6, static_cast(data)); + //loggers::get_instance().log_msg("ethernet_layer::receive_data: dst: ", dst); + // Extract source MAC Address + OCTETSTRING src = OCTETSTRING(6, 6 + static_cast(data)); + //loggers::get_instance().log_msg("ethernet_layer::receive_data: src: ", src); + // Extract ethertype + OCTETSTRING proto = OCTETSTRING(2, 2 + static_cast(data)); + //loggers::get_instance().log_msg("ethernet_layer::receive_data: proto: ", proto); + data = OCTETSTRING(data.lengthof() - 14, 14 + static_cast(data)); + // Update params + CHARSTRING s = oct2str(dst); + params.insert(std::pair(params::mac_dst, std::string(static_cast(s)))); + s = oct2str(src); + params.insert(std::pair(params::mac_src, std::string(static_cast(s)))); + //loggers::get_instance().log_msg("ethernet_layer::receive_data: payload for upper layer:", data); + + receive_to_all_layers(data, params); +} + +ethernet_layer_factory ethernet_layer_factory::_f; diff --git a/ccsrc/Protocols/ETH/ethernet_layer.hh b/ccsrc/Protocols/ETH/ethernet_layer.hh index 7ee8502e080b99c5e4b9d2647a53cb18444e2047..e4d8b358827880668d4d103e721bc80cbd0de99b 100644 --- a/ccsrc/Protocols/ETH/ethernet_layer.hh +++ b/ccsrc/Protocols/ETH/ethernet_layer.hh @@ -1,48 +1,48 @@ -/*! - * \file udp_layer.hh - * \brief Header file for ITS UDP/IP protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "params.hh" -#include "t_layer.hh" - -class ethernet_layer : public layer { - params _params; //! Layer parameters - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the ethernet_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - ethernet_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~ethernet_layer(){}; - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class ethernet_layer +/*! + * \file udp_layer.hh + * \brief Header file for ITS UDP/IP protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "params.hh" +#include "t_layer.hh" + +class ethernet_layer : public layer { + params _params; //! Layer parameters + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the ethernet_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + ethernet_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~ethernet_layer(){}; + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class ethernet_layer diff --git a/ccsrc/Protocols/ETH/ethernet_layer_factory.hh b/ccsrc/Protocols/ETH/ethernet_layer_factory.hh index b6eaac81999672fcaf998bfd4c33419e8df31fa4..7adf9f4c242fcb60c532a04e7c2b08d9ed2ab51b 100644 --- a/ccsrc/Protocols/ETH/ethernet_layer_factory.hh +++ b/ccsrc/Protocols/ETH/ethernet_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file ethernet_layer_factory.hh - * \brief Header file for ITS Ethernet protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "ethernet_layer.hh" - -/*! - * \class ethernet_layer_factory - * \brief This class provides a factory class to create an ethernet_layer class instance - */ -class ethernet_layer_factory : public layer_factory { - static ethernet_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the ethernet_layer_factory class - * \remark The ETH layer identifier is ETH - */ - ethernet_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("ETH", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new ethernet_layer(p_type, p_param); }; -}; // End of class ethernet_layer_factory +/*! + * \file ethernet_layer_factory.hh + * \brief Header file for ITS Ethernet protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "ethernet_layer.hh" + +/*! + * \class ethernet_layer_factory + * \brief This class provides a factory class to create an ethernet_layer class instance + */ +class ethernet_layer_factory : public layer_factory { + static ethernet_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the ethernet_layer_factory class + * \remark The ETH layer identifier is ETH + */ + ethernet_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("ETH", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new ethernet_layer(p_type, p_param); }; +}; // End of class ethernet_layer_factory diff --git a/ccsrc/Protocols/ETH/module.mk b/ccsrc/Protocols/ETH/module.mk index e81733a3181d060340ef98168c6c0ff6f2d77755..eb2f4a85f4af2a627f6734cd4baed7cf24d2a9c9 100644 --- a/ccsrc/Protocols/ETH/module.mk +++ b/ccsrc/Protocols/ETH/module.mk @@ -1,3 +1,3 @@ -sources := ethernet_layer.cc -includes := . - +sources := ethernet_layer.cc +includes := . + diff --git a/ccsrc/Protocols/GeoNetworking/decoding_context.hh b/ccsrc/Protocols/GeoNetworking/decoding_context.hh index 7221d54cd66d973fc6b5ff683a7c7be74580a2fd..d5c26adba7b587984d80368a0fed6f89af2e473a 100644 --- a/ccsrc/Protocols/GeoNetworking/decoding_context.hh +++ b/ccsrc/Protocols/GeoNetworking/decoding_context.hh @@ -1,37 +1,37 @@ -#pragma once - -#include - -class decoding_context { - unsigned char _next_header; - unsigned char _header_type; - unsigned char _header_sub_type; - unsigned char _traffic_class; - unsigned int _lifetime; - unsigned int _length; - -public: - explicit decoding_context() { reset(); }; - ~decoding_context(){}; - inline void reset() { - _next_header = 0xff; - _header_type = 0xff; - _header_sub_type = 0xff; - _lifetime = 0; - _length = -1; - }; - -public: - inline unsigned char get_next_header() { return _next_header; }; - inline void set_next_header(const unsigned char p_next_header) { _next_header = p_next_header; }; - inline unsigned char get_header_type() { return _header_type; }; - inline void set_header_type(const unsigned char p_header_type) { _header_type = p_header_type; }; - inline unsigned char get_header_sub_type() { return _header_sub_type; }; - inline void set_header_sub_type(const unsigned char p_header_sub_type) { _header_sub_type = p_header_sub_type; }; - inline unsigned char get_traffic_class() { return _traffic_class; }; - inline void set_traffic_class(const unsigned char p_traffic_class) { _traffic_class = p_traffic_class; }; - inline unsigned int get_lifetime() { return _lifetime; }; - inline void set_lifetime(const unsigned int p_lifetime) { _lifetime = p_lifetime; }; - inline unsigned int get_length() { return _length; }; - inline void set_length(const unsigned int p_length) { _length = p_length; }; -}; // End of class decoding_context +#pragma once + +#include + +class decoding_context { + unsigned char _next_header; + unsigned char _header_type; + unsigned char _header_sub_type; + unsigned char _traffic_class; + unsigned int _lifetime; + unsigned int _length; + +public: + explicit decoding_context() { reset(); }; + ~decoding_context(){}; + inline void reset() { + _next_header = 0xff; + _header_type = 0xff; + _header_sub_type = 0xff; + _lifetime = 0; + _length = -1; + }; + +public: + inline unsigned char get_next_header() { return _next_header; }; + inline void set_next_header(const unsigned char p_next_header) { _next_header = p_next_header; }; + inline unsigned char get_header_type() { return _header_type; }; + inline void set_header_type(const unsigned char p_header_type) { _header_type = p_header_type; }; + inline unsigned char get_header_sub_type() { return _header_sub_type; }; + inline void set_header_sub_type(const unsigned char p_header_sub_type) { _header_sub_type = p_header_sub_type; }; + inline unsigned char get_traffic_class() { return _traffic_class; }; + inline void set_traffic_class(const unsigned char p_traffic_class) { _traffic_class = p_traffic_class; }; + inline unsigned int get_lifetime() { return _lifetime; }; + inline void set_lifetime(const unsigned int p_lifetime) { _lifetime = p_lifetime; }; + inline unsigned int get_length() { return _length; }; + inline void set_length(const unsigned int p_length) { _length = p_length; }; +}; // End of class decoding_context diff --git a/ccsrc/Protocols/GeoNetworking/encoding_context.hh b/ccsrc/Protocols/GeoNetworking/encoding_context.hh index 74ace5c2b6ad217d7f2c033f01cde9af86ec8e40..82130c36a1765e0e7e423c6df7ff1d5524056db2 100644 --- a/ccsrc/Protocols/GeoNetworking/encoding_context.hh +++ b/ccsrc/Protocols/GeoNetworking/encoding_context.hh @@ -1,33 +1,33 @@ -#pragma once - -#include - -class encoding_context { - unsigned char _basic_header; - unsigned char _next_header; - unsigned char _header_type; - unsigned int _length_position; - unsigned int _length; - -public: - explicit encoding_context() { reset(); } - inline void reset() { - _basic_header = 0xff; - _next_header = 0xff; - _header_type = 0xff; - _length_position = -1; - _length = -1; - } - -public: - inline unsigned char get_basic_header() { return _basic_header; }; - inline void set_basic_header(const unsigned char p_basic_header) { _basic_header = p_basic_header; }; - inline unsigned char get_next_header() { return _next_header; }; - inline void set_next_header(const unsigned char p_next_header) { _next_header = p_next_header; }; - inline unsigned char get_header_type() { return _header_type; }; - inline void set_header_type(const unsigned char p_header_type) { _header_type = p_header_type; }; - inline unsigned int get_length_position() { return _length_position; }; - inline void set_length_position(const unsigned int p_length_position) { _length_position = p_length_position; }; - inline unsigned int get_length() { return _length; }; - inline void set_length(const unsigned int p_length) { _length = p_length; }; -}; // End of class encoding_context +#pragma once + +#include + +class encoding_context { + unsigned char _basic_header; + unsigned char _next_header; + unsigned char _header_type; + unsigned int _length_position; + unsigned int _length; + +public: + explicit encoding_context() { reset(); } + inline void reset() { + _basic_header = 0xff; + _next_header = 0xff; + _header_type = 0xff; + _length_position = -1; + _length = -1; + } + +public: + inline unsigned char get_basic_header() { return _basic_header; }; + inline void set_basic_header(const unsigned char p_basic_header) { _basic_header = p_basic_header; }; + inline unsigned char get_next_header() { return _next_header; }; + inline void set_next_header(const unsigned char p_next_header) { _next_header = p_next_header; }; + inline unsigned char get_header_type() { return _header_type; }; + inline void set_header_type(const unsigned char p_header_type) { _header_type = p_header_type; }; + inline unsigned int get_length_position() { return _length_position; }; + inline void set_length_position(const unsigned int p_length_position) { _length_position = p_length_position; }; + inline unsigned int get_length() { return _length; }; + inline void set_length(const unsigned int p_length) { _length = p_length; }; +}; // End of class encoding_context diff --git a/ccsrc/Protocols/GeoNetworking/geonetworking_codec.cc b/ccsrc/Protocols/GeoNetworking/geonetworking_codec.cc index ec18e96c8055cf05e0ed8a3620893f5f8086d279..b88306344b973d8e86acd84cb7470448e025d832 100644 --- a/ccsrc/Protocols/GeoNetworking/geonetworking_codec.cc +++ b/ccsrc/Protocols/GeoNetworking/geonetworking_codec.cc @@ -1,418 +1,418 @@ -#include -//#include - -#include "geonetworking_codec.hh" -#include "loggers.hh" - -#include "etsi_ts103097_data_codec.hh" - -#include "LibItsGeoNetworking_TypesAndValues.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -int geonetworking_codec::encode(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> geonetworking_codec::encode (1): ", (const Base_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - - _ec.reset(); - - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - // Overwrite the payload length - if (_ec.get_length() != (unsigned int)-1) { - loggers::get_instance().log("geonetworking_codec::encode: length=%d - plLength_position = %d - plLength = %d", data.lengthof(), _ec.get_length_position(), - _ec.get_length()); - unsigned char b[] = {(unsigned char)((_ec.get_length() & 0x0000FF00) >> 8), (unsigned char)_ec.get_length()}; - OCTETSTRING rpl(sizeof(b), b); - loggers::get_instance().log_msg("geonetworking_codec::encode: rpl=", rpl); - data = replace(data, _ec.get_length_position(), rpl.lengthof(), rpl); - loggers::get_instance().log_msg("geonetworking_codec::encode: after replace: ", data); - } - loggers::get_instance().log_msg("geonetworking_codec::encode: After encoding: ", data); - - loggers::get_instance().log("<<< geonetworking_codec::encode"); - return 0; -} - -int geonetworking_codec::encode(const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p_gnNonSecuredPacket, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> geonetworking_codec::encode (2): ", (const Base_Type &)p_gnNonSecuredPacket); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - encode_(p_gnNonSecuredPacket, *p_gnNonSecuredPacket.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - // Overwrite the payload length - if (_ec.get_length() != (unsigned int)-1) { - loggers::get_instance().log("geonetworking_codec::encode: length=%d - plLength_position = %d - plLength = %d", data.lengthof(), _ec.get_length_position(), - _ec.get_length()); - unsigned char b[] = {(unsigned char)((_ec.get_length() & 0x0000FF00) >> 8), (unsigned char)_ec.get_length()}; - OCTETSTRING rpl(sizeof(b), b); - loggers::get_instance().log_msg("geonetworking_codec::encode: rpl=", rpl); - data = replace(data, _ec.get_length_position(), rpl.lengthof(), rpl); - loggers::get_instance().log_msg("geonetworking_codec::encode: after replace: ", data); - } - loggers::get_instance().log_msg("geonetworking_codec::encode: After encoding: ", data); - - loggers::get_instance().log("<<< geonetworking_codec::encode"); - return 0; -} - -int geonetworking_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - // loggers::get_instance().log(">>> geonetworking_codec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); - // loggers::get_instance().log_msg(">>> geonetworking_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - // loggers::get_instance().log("geonetworking_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - // loggers::get_instance().log("geonetworking_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - // r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if ((_ec.get_basic_header() == 0x02) && (std::string(r.fld_descr(i)->name).compare("@LibItsGeoNetworking_TypesAndValues.GeoNetworkingPacket.packet") == - 0)) { // Encoding secured GeoNetworking packet, unsecured GN message was already encoded using encvalue - // loggers::get_instance().log("geonetworking_codec::encode_: Skip it"); - continue; - } - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - // loggers::get_instance().warning("geonetworking_codec::encode_: -1 result code returned"); - return -1; - } - } - } // End of 'for' statement - } else if (std::string(type.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.ExtendedHeader") == 0) { - const OPTIONAL &v = - dynamic_cast &>(type); - // loggers::get_instance().log("geonetworking_codec::encode_: ExtendedHeader present: %d", v.is_present()); - if (v.is_present()) { - if (encode_extendedHeader(static_cast(*v.get_opt_value()), encoding_buffer) == -1) { - loggers::get_instance().warning("geonetworking_codec::encode_: -1 result code returned"); - return -1; - } - } - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.GnNonSecuredPacket.payload") == 0) { - const OPTIONAL &v = - dynamic_cast &>(type); - // loggers::get_instance().log("geonetworking_codec::encode_: GnRawPayload present: %d", v.is_present()); - if (v.is_present()) { - const LibItsGeoNetworking__TypesAndValues::GnRawPayload &p = static_cast(*v.get_opt_value()); - if (encode_(p, *p.get_descriptor() /*LibItsGeoNetworking__TypesAndValues::GnRawPayload_descr_*/, encoding_buffer) == -1) { - loggers::get_instance().warning("geonetworking_codec::encode_: -1 result code returned"); - return -1; - } - // Store playload length and continue encoding - _ec.set_length(p.lengthof()); - // loggers::get_instance().log("geonetworking_codec::encode_: Storing payload length %d for %s", _ec.get_length(), p.get_descriptor()->name); - } - } else if (std::string(field_descriptor.name).compare("@EtsiTs103097Module.EtsiTs103097Data") == 0) { - const EtsiTs103097Module::EtsiTs103097Data &ieee_1609dot2_data = static_cast(type); - // loggers::get_instance().log_msg("geonetworking_codec::encode_: Encode secured message= ", ieee_1609dot2_data); - etsi_ts103097_data_codec codec; - OCTETSTRING os; - codec.encode(ieee_1609dot2_data, os); - if (os.lengthof() == 0) { - loggers::get_instance().warning("geonetworking_codec::encode_: Failed to encode EtsiTs103097Data"); - return -1; - } - // loggers::get_instance().log_msg("geonetworking_codec::encode_: ", os); - encoding_buffer.put_string(os); - } else { - // loggers::get_instance().log("geonetworking_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.BasicHeader.nextHeader") == 0) { - // Store NextHeader field value and continue encoding - _ec.set_basic_header((unsigned int)dynamic_cast(type).as_int()); - // loggers::get_instance().log("geonetworking_codec::encode_: Storing basic_header %d for %s", _ec.get_next_header(), field_descriptor.name); - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.nextHeader") == 0) { - // Store NextHeader field value and continue encoding - _ec.set_next_header((unsigned int)dynamic_cast(type).as_int()); - // loggers::get_instance().log("geonetworking_codec::encode_: Storing next_header %d for %s", _ec.get_next_header(), field_descriptor.name); - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.headerType") == 0) { - // Store HeaderType field value and continue encoding - _ec.set_header_type((unsigned int)dynamic_cast(type).as_int()); - // loggers::get_instance().log("geonetworking_codec::encode_: Storing header_type %d for %s", _ec.get_header_type(), field_descriptor.name); - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.plLength") == 0) { - // Store TTCN_Buffer position and continue encoding - _ec.set_length_position(encoding_buffer.get_len()); - // loggers::get_instance().log("geonetworking_codec::encode_: Storing position %d for %s", _ec.get_length_position(), field_descriptor.name); - } - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - - // loggers::get_instance().log_to_hexa("<<< geonetworking_codec::encode_: ", encoding_buffer); - return 0; -} - -int geonetworking_codec::decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, params *params) { - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - - _dc.reset(); - - _params = params; - - loggers::get_instance().log_to_hexa(">>> geonetworking_codec::decode: decoding_buffer=", decoding_buffer); - decode_(msg, *msg.get_descriptor(), decoding_buffer); - loggers::get_instance().log("geonetworking_codec::decode: After decoding, payload: plLength=%d", _dc.get_length()); - // Set layer parameters - if (_params != NULL) { - (*_params)[params::gn_next_header] = std::to_string((unsigned int)_dc.get_next_header()); - (*_params)[params::gn_header_type] = std::to_string((unsigned int)_dc.get_header_type()); - (*_params)[params::gn_header_sub_type] = std::to_string((unsigned int)_dc.get_header_sub_type()); - (*_params)[params::gn_traffic_class] = std::to_string((unsigned int)_dc.get_traffic_class()); - (*_params)[params::gn_lifetime] = std::to_string(_dc.get_lifetime()); - params->log(); - } - - loggers::get_instance().log_msg("<<< geonetworking_codec::decode: ", (const Base_Type &)msg); - return 0; -} - -int geonetworking_codec::decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer) { - // loggers::get_instance().log(">>> geonetworking_codec::decode_: processing %s/%s (%d,%d,%p)", type.get_descriptor()->name, field_descriptor.name, - // decoding_buffer.get_len(), decoding_buffer.get_pos(), decoding_buffer.get_read_data()); - - if (dynamic_cast(&type) != NULL) { - Record_Type &r = (Record_Type &)type; - // loggers::get_instance().log("geonetworking_codec::decode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - // loggers::get_instance().log("geonetworking_codec::decode_: processing %s/%s/%s", r.fld_name(i), r.fld_descr(i)->name, - // r.get_at(i)->get_descriptor()->name); - if (decode_(*dynamic_cast(r.get_at(i)), *(r.fld_descr(i)), decoding_buffer) == -1) { - loggers::get_instance().warning("geonetworking_codec::decode_: -1 result code returned"); - return -1; - } - } // End of 'for' statement - // Save data for upper layer - if (std::string(r.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.Lifetime") == 0) { - LibItsGeoNetworking__TypesAndValues::Lifetime &l = static_cast(r); - unsigned int base = 0; - switch (l.ltBase().as_int()) { - case LibItsGeoNetworking__TypesAndValues::LtBase::e__50ms: - base = 50; - break; - case LibItsGeoNetworking__TypesAndValues::LtBase::e__1s: - base = 1000; - break; - case LibItsGeoNetworking__TypesAndValues::LtBase::e__10s: - base = 10000; - break; - case LibItsGeoNetworking__TypesAndValues::LtBase::e__100s: - base = 100000; - break; - } // End of 'switch' statement - _dc.set_lifetime(base * static_cast(l.multiplier())); - // loggers::get_instance().log("geonetworking_codec::decode_: Lifetime calculus: %d - %s", _dc.get_lifetime(), - // std::to_string(_dc.get_lifetime()).c_str()); - } else if (std::string(type.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.TrafficClass") == 0) { - LibItsGeoNetworking__TypesAndValues::TrafficClass &t = static_cast(r); - _dc.set_traffic_class((t.scf().as_int() << 7) | (t.channelOffload() << 6) | (t.tcId() & 0x3f)); // ETSI EN 302 636-4-1 chapter 8.7.5 - } - } else if (std::string(type.get_descriptor()->name).compare("@Ieee1609Dot2.Ieee1609Dot2Data") == 0) { - dynamic_cast &>(type).set_to_omit(); // TODO Add security support - } else { - // loggers::get_instance().log("geonetworking_codec::decode_ (else): processing type %s/%s - optional:%d", type.get_descriptor()->name, - // field_descriptor.name, type.is_optional()); - if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.nextHeader") == 0) { - // Decode NextHeader data structure - type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); - // Store NextHeader field value and continue decoding - _dc.set_next_header((unsigned int)dynamic_cast(type).as_int()); - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.headerTST") == 0) { - decode_headerTST(static_cast(type), decoding_buffer); - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.GnNonSecuredPacket.extendedHeader") == 0) { - // Decode ExtendedHeader data structure - LibItsGeoNetworking__TypesAndValues::ExtendedHeader e; - decode_extendedHeader(e, decoding_buffer); - if (e.is_bound()) { - dynamic_cast &>(type) = OPTIONAL(e); - // loggers::get_instance().log_msg("geonetworking_codec::decode_: Set OPTIONAL to ", type); - } else { - // loggers::get_instance().log("geonetworking_codec::decode_: Set OPTIONAL to omit"); - dynamic_cast &>(type).set_to_omit(); - } - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.GnNonSecuredPacket.payload") == 0) { - // Decode raw payload data structure - OCTETSTRING s(decoding_buffer.get_len() - decoding_buffer.get_pos(), decoding_buffer.get_data() + decoding_buffer.get_pos()); - // loggers::get_instance().log_msg("geonetworking_codec::decode_: s=", s); - const unsigned char *p = static_cast(s); - if (p == NULL) { - loggers::get_instance().warning("geonetworking_codec::encode_: Static cast error"); - return -1; - } - // Align the payload length with the specified plLenght value - // loggers::get_instance().log("geonetworking_codec::decode_: Payload: Decoded payload length: %d", _dc.get_length()); - OCTETSTRING os; - if (_dc.get_length() != 0) { - if ((unsigned char)s.lengthof() <= _dc.get_length()) { - os = OCTETSTRING(s.lengthof(), p); - (*_params)[params::gn_payload] = static_cast(oct2str(os)); - } else { - os = OCTETSTRING(_dc.get_length(), p); - (*_params)[params::gn_payload] = static_cast(oct2str(os)); - } - } else { - os = OCTETSTRING(0, nullptr); - (*_params)[params::gn_payload] = ""; - } - // loggers::get_instance().log_msg("geonetworking_codec::decode_: Payload: os: ", os); - // loggers::get_instance().log("geonetworking_codec::decode_: Payload: '%s'", (*_params)[params::gn_payload].c_str()); - if (os.lengthof() != 0) { - dynamic_cast &>(type) = OPTIONAL(os); - // loggers::get_instance().log_msg("geonetworking_codec::decode_: Set OPTIONAL to ", type); - } else { - // loggers::get_instance().log("geonetworking_codec::decode_: Set OPTIONAL to omit"); - dynamic_cast &>(type).set_to_omit(); - } - } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.plLength") == 0) { - // Decode plLength data structure - type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); - // Store playload length and continue decoding - _dc.set_length((unsigned int)static_cast(dynamic_cast(type))); - } else { - type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); - } - } - - // loggers::get_instance().log_msg("<<< geonetworking_codec::decode_: ", type); - // loggers::get_instance().log_to_hexa("<<< geonetworking_codec::decode_: decoding_buffer=", decoding_buffer); - - return 0; -} - -int geonetworking_codec::encode_extendedHeader(const LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &encoding_buffer) { - // loggers::get_instance().log(">>> geonetworking_codec::encode_extendedHeader: processing %s", u.get_descriptor()->name); - - int result = -1; - switch (u.get_selection()) { - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::UNBOUND_VALUE: - TTCN_error("geonetworking_codec::encode_extendedHeader: Invalid selection in unbound union"); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_geoUnicastHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.geoUnicastHeader().get_descriptor()->name); - result = encode_(u.geoUnicastHeader(), *u.geoUnicastHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_tsbHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.tsbHeader().get_descriptor()->name); - result = encode_(u.tsbHeader(), *u.tsbHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_shbHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.shbHeader().get_descriptor()->name); - result = encode_(u.shbHeader(), *u.shbHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_geoBroadcastHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.geoBroadcastHeader().get_descriptor()->name); - result = encode_(u.geoBroadcastHeader(), *u.geoBroadcastHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_geoAnycastHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.geoAnycastHeader().get_descriptor()->name); - result = encode_(u.geoAnycastHeader(), *u.geoAnycastHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_beaconHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.beaconHeader().get_descriptor()->name); - result = encode_(u.beaconHeader(), *u.beaconHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_anyHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.anyHeader().get_descriptor()->name); - result = encode_(u.anyHeader(), *u.anyHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_lsRequestHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.lsRequestHeader().get_descriptor()->name); - result = encode_(u.lsRequestHeader(), *u.lsRequestHeader().get_descriptor(), encoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_lsReplyHeader: - // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.lsReplyHeader().get_descriptor()->name); - result = encode_(u.lsReplyHeader(), *u.lsReplyHeader().get_descriptor(), encoding_buffer); - break; - default: - TTCN_error("geonetworking_codec::encode_extendedHeader: Invalid selection in union is_bound"); - } // End of 'switch' statement - - return result; -} - -int geonetworking_codec::decode_headerTST(LibItsGeoNetworking__TypesAndValues::HeaderTST &u, TTCN_Buffer &decoding_buffer) { - // loggers::get_instance().log(">>> geonetworking_codec::decode_headerTST: processing %s", u.get_descriptor()->name); - - // Decode HeaderTST data structure - _dc.set_header_type(*(decoding_buffer.get_data() + decoding_buffer.get_pos()) >> 4); - _dc.set_header_sub_type(*(decoding_buffer.get_data() + decoding_buffer.get_pos()) & 0x0F); - // loggers::get_instance().log("geonetworking_codec::decode_: headerTST selectors: _dc.header_type = %d - _dc.header_sub_type = %d", _dc.get_header_type(), - // _dc.get_header_sub_type()); LibItsGeoNetworking__TypesAndValues::HeaderTST & u = dynamic_cast(u); - switch (_dc.get_header_type()) { - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoUnicast: - decode_(u.geoUnicastHdr(), *u.geoUnicastHdr().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__topologicallyScopedBroadcast: - decode_(u.tsbHdr(), *u.tsbHdr().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoBroadcast: - decode_(u.geoBroadcastHdr(), *u.geoBroadcastHdr().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoAnycast: - decode_(u.geoAnycastHdr(), *u.geoAnycastHdr().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__beacon: - decode_(u.beaconHdr(), *u.beaconHdr().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__locationService: - decode_(u.lsHdr(), *u.lsHdr().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__any: - decode_(u.anyHdr(), *u.anyHdr().get_descriptor(), decoding_buffer); - break; - default: - TTCN_error("geonetworking_codec::decode_: Not processed, _dc.header_type = %d - _dc.header_sub_type = %d", _dc.get_header_type(), - _dc.get_header_sub_type()); - } // End of 'switch' statement - - return 0; -} - -int geonetworking_codec::decode_extendedHeader(LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &decoding_buffer) { - // loggers::get_instance().log(">>> geonetworking_codec::decode_extendedHeader: processing %s", u.get_descriptor()->name); - - switch (_dc.get_header_type()) { - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoUnicast: - decode_(u.geoUnicastHeader(), *u.geoUnicastHeader().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__topologicallyScopedBroadcast: - if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeTSB::e__multiHop) { - decode_(u.tsbHeader(), *u.tsbHeader().get_descriptor(), decoding_buffer); - } else if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeTSB::e__singleHop) { - decode_(u.shbHeader(), *u.shbHeader().get_descriptor(), decoding_buffer); - } else { - TTCN_error("geonetworking_codec::decode_headerTST: TSB subtype not processed, See ETSI EN 302 636-4-1 Clause 9.7.4 Encoding of the HT and HST fields"); - } - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoBroadcast: - decode_(u.geoBroadcastHeader(), *u.geoBroadcastHeader().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoAnycast: - decode_(u.geoAnycastHeader(), *u.geoAnycastHeader().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__beacon: - decode_(u.beaconHeader(), *u.beaconHeader().get_descriptor(), decoding_buffer); - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__locationService: - if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeLs::e__lsRequest) { - decode_(u.lsRequestHeader(), *u.lsRequestHeader().get_descriptor(), decoding_buffer); - } else if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeLs::e__lsReply) { - decode_(u.lsReplyHeader(), *u.lsReplyHeader().get_descriptor(), decoding_buffer); - } else { - TTCN_error("geonetworking_codec::decode_headerTST: Location service subtype not processed, See ETSI EN 302 636-4-1 Clause 9.7.4 Encoding of the HT and " - "HST fields"); - } - break; - case LibItsGeoNetworking__TypesAndValues::HeaderType::e__any: - decode_(u.anyHeader(), *u.anyHeader().get_descriptor(), decoding_buffer); - break; - default: - TTCN_error("geonetworking_codec::decode_headerTST: Not processed, _dc.header_type = %d - _dc.header_sub_type = %d, See ETSI EN 302 636-4-1 Clause 9.7.4 " - "Encoding of the HT and HST fields", - _dc.get_header_type(), _dc.get_header_sub_type()); - } // End of 'switch' statement - - return 0; -} +#include +//#include + +#include "geonetworking_codec.hh" +#include "loggers.hh" + +#include "etsi_ts103097_data_codec.hh" + +#include "LibItsGeoNetworking_TypesAndValues.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +int geonetworking_codec::encode(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> geonetworking_codec::encode (1): ", (const Base_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + + _ec.reset(); + + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + // Overwrite the payload length + if (_ec.get_length() != (unsigned int)-1) { + loggers::get_instance().log("geonetworking_codec::encode: length=%d - plLength_position = %d - plLength = %d", data.lengthof(), _ec.get_length_position(), + _ec.get_length()); + unsigned char b[] = {(unsigned char)((_ec.get_length() & 0x0000FF00) >> 8), (unsigned char)_ec.get_length()}; + OCTETSTRING rpl(sizeof(b), b); + loggers::get_instance().log_msg("geonetworking_codec::encode: rpl=", rpl); + data = replace(data, _ec.get_length_position(), rpl.lengthof(), rpl); + loggers::get_instance().log_msg("geonetworking_codec::encode: after replace: ", data); + } + loggers::get_instance().log_msg("geonetworking_codec::encode: After encoding: ", data); + + loggers::get_instance().log("<<< geonetworking_codec::encode"); + return 0; +} + +int geonetworking_codec::encode(const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p_gnNonSecuredPacket, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> geonetworking_codec::encode (2): ", (const Base_Type &)p_gnNonSecuredPacket); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + encode_(p_gnNonSecuredPacket, *p_gnNonSecuredPacket.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + // Overwrite the payload length + if (_ec.get_length() != (unsigned int)-1) { + loggers::get_instance().log("geonetworking_codec::encode: length=%d - plLength_position = %d - plLength = %d", data.lengthof(), _ec.get_length_position(), + _ec.get_length()); + unsigned char b[] = {(unsigned char)((_ec.get_length() & 0x0000FF00) >> 8), (unsigned char)_ec.get_length()}; + OCTETSTRING rpl(sizeof(b), b); + loggers::get_instance().log_msg("geonetworking_codec::encode: rpl=", rpl); + data = replace(data, _ec.get_length_position(), rpl.lengthof(), rpl); + loggers::get_instance().log_msg("geonetworking_codec::encode: after replace: ", data); + } + loggers::get_instance().log_msg("geonetworking_codec::encode: After encoding: ", data); + + loggers::get_instance().log("<<< geonetworking_codec::encode"); + return 0; +} + +int geonetworking_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + // loggers::get_instance().log(">>> geonetworking_codec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); + // loggers::get_instance().log_msg(">>> geonetworking_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + // loggers::get_instance().log("geonetworking_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + // loggers::get_instance().log("geonetworking_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + // r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if ((_ec.get_basic_header() == 0x02) && (std::string(r.fld_descr(i)->name).compare("@LibItsGeoNetworking_TypesAndValues.GeoNetworkingPacket.packet") == + 0)) { // Encoding secured GeoNetworking packet, unsecured GN message was already encoded using encvalue + // loggers::get_instance().log("geonetworking_codec::encode_: Skip it"); + continue; + } + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + // loggers::get_instance().warning("geonetworking_codec::encode_: -1 result code returned"); + return -1; + } + } + } // End of 'for' statement + } else if (std::string(type.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.ExtendedHeader") == 0) { + const OPTIONAL &v = + dynamic_cast &>(type); + // loggers::get_instance().log("geonetworking_codec::encode_: ExtendedHeader present: %d", v.is_present()); + if (v.is_present()) { + if (encode_extendedHeader(static_cast(*v.get_opt_value()), encoding_buffer) == -1) { + loggers::get_instance().warning("geonetworking_codec::encode_: -1 result code returned"); + return -1; + } + } + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.GnNonSecuredPacket.payload") == 0) { + const OPTIONAL &v = + dynamic_cast &>(type); + // loggers::get_instance().log("geonetworking_codec::encode_: GnRawPayload present: %d", v.is_present()); + if (v.is_present()) { + const LibItsGeoNetworking__TypesAndValues::GnRawPayload &p = static_cast(*v.get_opt_value()); + if (encode_(p, *p.get_descriptor() /*LibItsGeoNetworking__TypesAndValues::GnRawPayload_descr_*/, encoding_buffer) == -1) { + loggers::get_instance().warning("geonetworking_codec::encode_: -1 result code returned"); + return -1; + } + // Store playload length and continue encoding + _ec.set_length(p.lengthof()); + // loggers::get_instance().log("geonetworking_codec::encode_: Storing payload length %d for %s", _ec.get_length(), p.get_descriptor()->name); + } + } else if (std::string(field_descriptor.name).compare("@EtsiTs103097Module.EtsiTs103097Data") == 0) { + const EtsiTs103097Module::EtsiTs103097Data &ieee_1609dot2_data = static_cast(type); + // loggers::get_instance().log_msg("geonetworking_codec::encode_: Encode secured message= ", ieee_1609dot2_data); + etsi_ts103097_data_codec codec; + OCTETSTRING os; + codec.encode(ieee_1609dot2_data, os); + if (os.lengthof() == 0) { + loggers::get_instance().warning("geonetworking_codec::encode_: Failed to encode EtsiTs103097Data"); + return -1; + } + // loggers::get_instance().log_msg("geonetworking_codec::encode_: ", os); + encoding_buffer.put_string(os); + } else { + // loggers::get_instance().log("geonetworking_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.BasicHeader.nextHeader") == 0) { + // Store NextHeader field value and continue encoding + _ec.set_basic_header((unsigned int)dynamic_cast(type).as_int()); + // loggers::get_instance().log("geonetworking_codec::encode_: Storing basic_header %d for %s", _ec.get_next_header(), field_descriptor.name); + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.nextHeader") == 0) { + // Store NextHeader field value and continue encoding + _ec.set_next_header((unsigned int)dynamic_cast(type).as_int()); + // loggers::get_instance().log("geonetworking_codec::encode_: Storing next_header %d for %s", _ec.get_next_header(), field_descriptor.name); + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.headerType") == 0) { + // Store HeaderType field value and continue encoding + _ec.set_header_type((unsigned int)dynamic_cast(type).as_int()); + // loggers::get_instance().log("geonetworking_codec::encode_: Storing header_type %d for %s", _ec.get_header_type(), field_descriptor.name); + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.plLength") == 0) { + // Store TTCN_Buffer position and continue encoding + _ec.set_length_position(encoding_buffer.get_len()); + // loggers::get_instance().log("geonetworking_codec::encode_: Storing position %d for %s", _ec.get_length_position(), field_descriptor.name); + } + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + + // loggers::get_instance().log_to_hexa("<<< geonetworking_codec::encode_: ", encoding_buffer); + return 0; +} + +int geonetworking_codec::decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, params *params) { + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + + _dc.reset(); + + _params = params; + + loggers::get_instance().log_to_hexa(">>> geonetworking_codec::decode: decoding_buffer=", decoding_buffer); + decode_(msg, *msg.get_descriptor(), decoding_buffer); + loggers::get_instance().log("geonetworking_codec::decode: After decoding, payload: plLength=%d", _dc.get_length()); + // Set layer parameters + if (_params != NULL) { + (*_params)[params::gn_next_header] = std::to_string((unsigned int)_dc.get_next_header()); + (*_params)[params::gn_header_type] = std::to_string((unsigned int)_dc.get_header_type()); + (*_params)[params::gn_header_sub_type] = std::to_string((unsigned int)_dc.get_header_sub_type()); + (*_params)[params::gn_traffic_class] = std::to_string((unsigned int)_dc.get_traffic_class()); + (*_params)[params::gn_lifetime] = std::to_string(_dc.get_lifetime()); + params->log(); + } + + loggers::get_instance().log_msg("<<< geonetworking_codec::decode: ", (const Base_Type &)msg); + return 0; +} + +int geonetworking_codec::decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer) { + // loggers::get_instance().log(">>> geonetworking_codec::decode_: processing %s/%s (%d,%d,%p)", type.get_descriptor()->name, field_descriptor.name, + // decoding_buffer.get_len(), decoding_buffer.get_pos(), decoding_buffer.get_read_data()); + + if (dynamic_cast(&type) != NULL) { + Record_Type &r = (Record_Type &)type; + // loggers::get_instance().log("geonetworking_codec::decode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + // loggers::get_instance().log("geonetworking_codec::decode_: processing %s/%s/%s", r.fld_name(i), r.fld_descr(i)->name, + // r.get_at(i)->get_descriptor()->name); + if (decode_(*dynamic_cast(r.get_at(i)), *(r.fld_descr(i)), decoding_buffer) == -1) { + loggers::get_instance().warning("geonetworking_codec::decode_: -1 result code returned"); + return -1; + } + } // End of 'for' statement + // Save data for upper layer + if (std::string(r.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.Lifetime") == 0) { + LibItsGeoNetworking__TypesAndValues::Lifetime &l = static_cast(r); + unsigned int base = 0; + switch (l.ltBase().as_int()) { + case LibItsGeoNetworking__TypesAndValues::LtBase::e__50ms: + base = 50; + break; + case LibItsGeoNetworking__TypesAndValues::LtBase::e__1s: + base = 1000; + break; + case LibItsGeoNetworking__TypesAndValues::LtBase::e__10s: + base = 10000; + break; + case LibItsGeoNetworking__TypesAndValues::LtBase::e__100s: + base = 100000; + break; + } // End of 'switch' statement + _dc.set_lifetime(base * static_cast(l.multiplier())); + // loggers::get_instance().log("geonetworking_codec::decode_: Lifetime calculus: %d - %s", _dc.get_lifetime(), + // std::to_string(_dc.get_lifetime()).c_str()); + } else if (std::string(type.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.TrafficClass") == 0) { + LibItsGeoNetworking__TypesAndValues::TrafficClass &t = static_cast(r); + _dc.set_traffic_class((t.scf().as_int() << 7) | (t.channelOffload() << 6) | (t.tcId() & 0x3f)); // ETSI EN 302 636-4-1 chapter 8.7.5 + } + } else if (std::string(type.get_descriptor()->name).compare("@Ieee1609Dot2.Ieee1609Dot2Data") == 0) { + dynamic_cast &>(type).set_to_omit(); // TODO Add security support + } else { + // loggers::get_instance().log("geonetworking_codec::decode_ (else): processing type %s/%s - optional:%d", type.get_descriptor()->name, + // field_descriptor.name, type.is_optional()); + if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.nextHeader") == 0) { + // Decode NextHeader data structure + type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); + // Store NextHeader field value and continue decoding + _dc.set_next_header((unsigned int)dynamic_cast(type).as_int()); + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.headerTST") == 0) { + decode_headerTST(static_cast(type), decoding_buffer); + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.GnNonSecuredPacket.extendedHeader") == 0) { + // Decode ExtendedHeader data structure + LibItsGeoNetworking__TypesAndValues::ExtendedHeader e; + decode_extendedHeader(e, decoding_buffer); + if (e.is_bound()) { + dynamic_cast &>(type) = OPTIONAL(e); + // loggers::get_instance().log_msg("geonetworking_codec::decode_: Set OPTIONAL to ", type); + } else { + // loggers::get_instance().log("geonetworking_codec::decode_: Set OPTIONAL to omit"); + dynamic_cast &>(type).set_to_omit(); + } + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.GnNonSecuredPacket.payload") == 0) { + // Decode raw payload data structure + OCTETSTRING s(decoding_buffer.get_len() - decoding_buffer.get_pos(), decoding_buffer.get_data() + decoding_buffer.get_pos()); + // loggers::get_instance().log_msg("geonetworking_codec::decode_: s=", s); + const unsigned char *p = static_cast(s); + if (p == NULL) { + loggers::get_instance().warning("geonetworking_codec::encode_: Static cast error"); + return -1; + } + // Align the payload length with the specified plLenght value + // loggers::get_instance().log("geonetworking_codec::decode_: Payload: Decoded payload length: %d", _dc.get_length()); + OCTETSTRING os; + if (_dc.get_length() != 0) { + if ((unsigned char)s.lengthof() <= _dc.get_length()) { + os = OCTETSTRING(s.lengthof(), p); + (*_params)[params::gn_payload] = static_cast(oct2str(os)); + } else { + os = OCTETSTRING(_dc.get_length(), p); + (*_params)[params::gn_payload] = static_cast(oct2str(os)); + } + } else { + os = OCTETSTRING(0, nullptr); + (*_params)[params::gn_payload] = ""; + } + // loggers::get_instance().log_msg("geonetworking_codec::decode_: Payload: os: ", os); + // loggers::get_instance().log("geonetworking_codec::decode_: Payload: '%s'", (*_params)[params::gn_payload].c_str()); + if (os.lengthof() != 0) { + dynamic_cast &>(type) = OPTIONAL(os); + // loggers::get_instance().log_msg("geonetworking_codec::decode_: Set OPTIONAL to ", type); + } else { + // loggers::get_instance().log("geonetworking_codec::decode_: Set OPTIONAL to omit"); + dynamic_cast &>(type).set_to_omit(); + } + } else if (std::string(field_descriptor.name).compare("@LibItsGeoNetworking_TypesAndValues.CommonHeader.plLength") == 0) { + // Decode plLength data structure + type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); + // Store playload length and continue decoding + _dc.set_length((unsigned int)static_cast(dynamic_cast(type))); + } else { + type.decode(field_descriptor, decoding_buffer, TTCN_EncDec::CT_RAW); + } + } + + // loggers::get_instance().log_msg("<<< geonetworking_codec::decode_: ", type); + // loggers::get_instance().log_to_hexa("<<< geonetworking_codec::decode_: decoding_buffer=", decoding_buffer); + + return 0; +} + +int geonetworking_codec::encode_extendedHeader(const LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &encoding_buffer) { + // loggers::get_instance().log(">>> geonetworking_codec::encode_extendedHeader: processing %s", u.get_descriptor()->name); + + int result = -1; + switch (u.get_selection()) { + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::UNBOUND_VALUE: + TTCN_error("geonetworking_codec::encode_extendedHeader: Invalid selection in unbound union"); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_geoUnicastHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.geoUnicastHeader().get_descriptor()->name); + result = encode_(u.geoUnicastHeader(), *u.geoUnicastHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_tsbHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.tsbHeader().get_descriptor()->name); + result = encode_(u.tsbHeader(), *u.tsbHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_shbHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.shbHeader().get_descriptor()->name); + result = encode_(u.shbHeader(), *u.shbHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_geoBroadcastHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.geoBroadcastHeader().get_descriptor()->name); + result = encode_(u.geoBroadcastHeader(), *u.geoBroadcastHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_geoAnycastHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.geoAnycastHeader().get_descriptor()->name); + result = encode_(u.geoAnycastHeader(), *u.geoAnycastHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_beaconHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.beaconHeader().get_descriptor()->name); + result = encode_(u.beaconHeader(), *u.beaconHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_anyHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.anyHeader().get_descriptor()->name); + result = encode_(u.anyHeader(), *u.anyHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_lsRequestHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.lsRequestHeader().get_descriptor()->name); + result = encode_(u.lsRequestHeader(), *u.lsRequestHeader().get_descriptor(), encoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_lsReplyHeader: + // loggers::get_instance().log("geonetworking_codec::encode_extendedHeader: processing type %s", u.lsReplyHeader().get_descriptor()->name); + result = encode_(u.lsReplyHeader(), *u.lsReplyHeader().get_descriptor(), encoding_buffer); + break; + default: + TTCN_error("geonetworking_codec::encode_extendedHeader: Invalid selection in union is_bound"); + } // End of 'switch' statement + + return result; +} + +int geonetworking_codec::decode_headerTST(LibItsGeoNetworking__TypesAndValues::HeaderTST &u, TTCN_Buffer &decoding_buffer) { + // loggers::get_instance().log(">>> geonetworking_codec::decode_headerTST: processing %s", u.get_descriptor()->name); + + // Decode HeaderTST data structure + _dc.set_header_type(*(decoding_buffer.get_data() + decoding_buffer.get_pos()) >> 4); + _dc.set_header_sub_type(*(decoding_buffer.get_data() + decoding_buffer.get_pos()) & 0x0F); + // loggers::get_instance().log("geonetworking_codec::decode_: headerTST selectors: _dc.header_type = %d - _dc.header_sub_type = %d", _dc.get_header_type(), + // _dc.get_header_sub_type()); LibItsGeoNetworking__TypesAndValues::HeaderTST & u = dynamic_cast(u); + switch (_dc.get_header_type()) { + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoUnicast: + decode_(u.geoUnicastHdr(), *u.geoUnicastHdr().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__topologicallyScopedBroadcast: + decode_(u.tsbHdr(), *u.tsbHdr().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoBroadcast: + decode_(u.geoBroadcastHdr(), *u.geoBroadcastHdr().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoAnycast: + decode_(u.geoAnycastHdr(), *u.geoAnycastHdr().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__beacon: + decode_(u.beaconHdr(), *u.beaconHdr().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__locationService: + decode_(u.lsHdr(), *u.lsHdr().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__any: + decode_(u.anyHdr(), *u.anyHdr().get_descriptor(), decoding_buffer); + break; + default: + TTCN_error("geonetworking_codec::decode_: Not processed, _dc.header_type = %d - _dc.header_sub_type = %d", _dc.get_header_type(), + _dc.get_header_sub_type()); + } // End of 'switch' statement + + return 0; +} + +int geonetworking_codec::decode_extendedHeader(LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &decoding_buffer) { + // loggers::get_instance().log(">>> geonetworking_codec::decode_extendedHeader: processing %s", u.get_descriptor()->name); + + switch (_dc.get_header_type()) { + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoUnicast: + decode_(u.geoUnicastHeader(), *u.geoUnicastHeader().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__topologicallyScopedBroadcast: + if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeTSB::e__multiHop) { + decode_(u.tsbHeader(), *u.tsbHeader().get_descriptor(), decoding_buffer); + } else if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeTSB::e__singleHop) { + decode_(u.shbHeader(), *u.shbHeader().get_descriptor(), decoding_buffer); + } else { + TTCN_error("geonetworking_codec::decode_headerTST: TSB subtype not processed, See ETSI EN 302 636-4-1 Clause 9.7.4 Encoding of the HT and HST fields"); + } + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoBroadcast: + decode_(u.geoBroadcastHeader(), *u.geoBroadcastHeader().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__geoAnycast: + decode_(u.geoAnycastHeader(), *u.geoAnycastHeader().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__beacon: + decode_(u.beaconHeader(), *u.beaconHeader().get_descriptor(), decoding_buffer); + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__locationService: + if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeLs::e__lsRequest) { + decode_(u.lsRequestHeader(), *u.lsRequestHeader().get_descriptor(), decoding_buffer); + } else if (_dc.get_header_sub_type() == LibItsGeoNetworking__TypesAndValues::HeaderSubTypeLs::e__lsReply) { + decode_(u.lsReplyHeader(), *u.lsReplyHeader().get_descriptor(), decoding_buffer); + } else { + TTCN_error("geonetworking_codec::decode_headerTST: Location service subtype not processed, See ETSI EN 302 636-4-1 Clause 9.7.4 Encoding of the HT and " + "HST fields"); + } + break; + case LibItsGeoNetworking__TypesAndValues::HeaderType::e__any: + decode_(u.anyHeader(), *u.anyHeader().get_descriptor(), decoding_buffer); + break; + default: + TTCN_error("geonetworking_codec::decode_headerTST: Not processed, _dc.header_type = %d - _dc.header_sub_type = %d, See ETSI EN 302 636-4-1 Clause 9.7.4 " + "Encoding of the HT and HST fields", + _dc.get_header_type(), _dc.get_header_sub_type()); + } // End of 'switch' statement + + return 0; +} diff --git a/ccsrc/Protocols/GeoNetworking/geonetworking_codec.hh b/ccsrc/Protocols/GeoNetworking/geonetworking_codec.hh index ed7370e5ada655af205598edb657b5e12dc3b74a..1cca7ec8f6abd3806db7b826d5d3c6750e598e24 100644 --- a/ccsrc/Protocols/GeoNetworking/geonetworking_codec.hh +++ b/ccsrc/Protocols/GeoNetworking/geonetworking_codec.hh @@ -1,49 +1,49 @@ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -#include "decoding_context.hh" -#include "encoding_context.hh" - -class Base_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsGeoNetworking__TypesAndValues { - class GeoNetworkingPdu; - class GnNonSecuredPacket; - class HeaderTST; - class ExtendedHeader; - class DecodedPayload; -}; // namespace LibItsGeoNetworking__TypesAndValues - -namespace LibItsSecurity__TypesAndValues { - class SecuredMessage; -}; - -class geonetworking_codec : public codec { - - encoding_context _ec; - decoding_context _dc; - - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - int encode_extendedHeader(const LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &encoding_buffer); - - int decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer); - int decode_headerTST(LibItsGeoNetworking__TypesAndValues::HeaderTST &u, TTCN_Buffer &decoding_buffer); - int decode_extendedHeader(LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &decodin_buffer); - -public: - explicit geonetworking_codec() - : codec(), _ec(), _dc(){}; - virtual ~geonetworking_codec(){}; - - virtual int encode(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, params *params = NULL); - - int encode(const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p_gnNonSecuredPacket, - OCTETSTRING & data); // TODO Duplicate code with virtual encode, to be enhanced -}; // End of class geonetworking_codec +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +#include "decoding_context.hh" +#include "encoding_context.hh" + +class Base_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsGeoNetworking__TypesAndValues { + class GeoNetworkingPdu; + class GnNonSecuredPacket; + class HeaderTST; + class ExtendedHeader; + class DecodedPayload; +}; // namespace LibItsGeoNetworking__TypesAndValues + +namespace LibItsSecurity__TypesAndValues { + class SecuredMessage; +}; + +class geonetworking_codec : public codec { + + encoding_context _ec; + decoding_context _dc; + + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + int encode_extendedHeader(const LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &encoding_buffer); + + int decode_(Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &decoding_buffer); + int decode_headerTST(LibItsGeoNetworking__TypesAndValues::HeaderTST &u, TTCN_Buffer &decoding_buffer); + int decode_extendedHeader(LibItsGeoNetworking__TypesAndValues::ExtendedHeader &u, TTCN_Buffer &decodin_buffer); + +public: + explicit geonetworking_codec() + : codec(), _ec(), _dc(){}; + virtual ~geonetworking_codec(){}; + + virtual int encode(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &msg, params *params = NULL); + + int encode(const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p_gnNonSecuredPacket, + OCTETSTRING & data); // TODO Duplicate code with virtual encode, to be enhanced +}; // End of class geonetworking_codec diff --git a/ccsrc/Protocols/GeoNetworking/geonetworking_layer.cc b/ccsrc/Protocols/GeoNetworking/geonetworking_layer.cc index 448412ec652ae0b90ceb2840b229fca1dcc2e87a..e0be2b47f4052b7f8cd0c64cff3ca6fcbe5ddace 100644 --- a/ccsrc/Protocols/GeoNetworking/geonetworking_layer.cc +++ b/ccsrc/Protocols/GeoNetworking/geonetworking_layer.cc @@ -1,947 +1,947 @@ -#include -#include -#include -#include - -#include "geonetworking_types.hh" - -#include "geonetworking_layer_factory.hh" - -#include "loggers.hh" - -#include "security_services.hh" - -#include "base_time.hh" - -#include "registration.hh" - -#include "converter.hh" - -using namespace LibItsGeoNetworking__TypesAndValues; - -geonetworking_layer::geonetworking_layer(const std::string &p_type, const std::string &p_param) - : t_layer(p_type), _params(), _codec(), _beacon(nullptr), _gbc_packet(nullptr), _shb_packet(nullptr), - _tsb_packet(nullptr), _uni_packet(nullptr), _ls_reply(nullptr), _location_table(), - _pass_beacon_table(), _device_mode{false}, _secured_mode{false}, _encrypted_mode{false}, _enable_security_checks{false}, - _sendData(), _timerid{0}, _sev{0}, _its{0}, _freq_nanosecs(0), _mask{0}, _sa{0}, _sequence_number{0}, _latitude{0}, _longitude{0} { - loggers::get_instance().log(">>> geonetworking_layer::geonetworking_layer: %s, %s", to_string().c_str(), p_param.c_str()); - - init(p_type, p_param); -} // End of constructor - -geonetworking_layer::~geonetworking_layer() { - loggers::get_instance().log(">>> geonetworking_layer::~geonetworking_layer"); - - if (_timerid != 0) { - timer_delete(_timerid); - } - if (_beacon != nullptr) { - delete _beacon; - } - if (_gbc_packet != nullptr) { - delete _gbc_packet; - } - if (_shb_packet != nullptr) { - delete _shb_packet; - } - if (_tsb_packet != nullptr) { - delete _tsb_packet; - } - if (_uni_packet != nullptr) { - delete _uni_packet; - } - if (_ls_reply != nullptr) { - delete _ls_reply; - } -} // End of destructor - -void geonetworking_layer::init(const std::string &p_type, const std::string &p_param) { - loggers::get_instance().log(">>> geonetworking_layer::init: %s, %s", to_string().c_str(), p_param.c_str()); - - // Setup parameters - params::convert(_params, p_param); - // Sanity checks - params::const_iterator it = _params.find(params::latitude); - if (it != _params.cend()) { - _latitude = converter::get_instance().string_to_int(it->second); - } - it = _params.find(params::longitude); - if (it != _params.cend()) { - _longitude = converter::get_instance().string_to_int(it->second); - } - OCTETSTRING ll_address; - it = _params.find(params::ll_address); - if (it != _params.cend()) { - ll_address = str2oct(CHARSTRING(it->second.c_str())); - } - INTEGER distanceA = 1000; // 1km - it = _params.find(params::distanceA); - if (it != _params.cend()) { - distanceA = converter::get_instance().string_to_int(it->second); - } - INTEGER distanceB = 1000; // 1Km - it = _params.find(params::distanceB); - if (it != _params.cend()) { - distanceB = converter::get_instance().string_to_int(it->second); - } - INTEGER angle = 0; - it = _params.find(params::angle); - if (it != _params.cend()) { - angle = converter::get_instance().string_to_int(it->second); - } - INTEGER station_type = 5; // passangerCar - it = _params.find(params::station_type); - if (it != _params.cend()) { - station_type = converter::get_instance().string_to_int(it->second); - } - INTEGER country = 0; - it = _params.find(params::country); - if (it != _params.cend()) { - country = converter::get_instance().string_to_int(it->second); - } - INTEGER type_of_address = 1; // Manual - it = _params.find(params::type_of_address); - if (it != _params.cend()) { - type_of_address = converter::get_instance().string_to_int(it->second); - } - - it = _params.find(params::device_mode); - if (it != _params.cend()) { - _device_mode = (1 == converter::get_instance().string_to_int(it->second)); - } - it = _params.find(params::secured_mode); - if (it != _params.cend()) { - _secured_mode = (1 == converter::get_instance().string_to_int(it->second)); - } else { - _params.insert(std::pair(std::string("secured_mode"), "0")); - } - it = _params.find(params::encrypted_mode); - if (it != _params.cend()) { - _encrypted_mode = (1 == converter::get_instance().string_to_int(it->second)); - } else { - _params.insert(std::pair(std::string("encrypted_mode"), "0")); - } - it = _params.find(params::enable_security_checks); - if (it != _params.cend()) { - _enable_security_checks = (1 == converter::get_instance().string_to_int(it->second)); - } - - // Add broadcast address if needed - it = _params.find(params::its_aid); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("its_aid"), "141")); - } - it = _params.find(params::mac_bc); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("mac_bc"), "FFFFFFFFFFFF")); - } - - // Set up default security parameters value - if (_secured_mode || _encrypted_mode) { - loggers::get_instance().log("geonetworking_layer::geonetworking_layer: Setup secured mode"); - setup_secured_mode(); - } - - // Automatic beaconing mode - fill_beacon(ll_address, station_type, country, type_of_address); - params::const_iterator i = _params.find(params::beaconing); - if ((i != _params.cend()) && (i->second.compare("1") == 0)) { // Immediate beaconing was requested - // Prepare beaconing operation - start_beaconing(); - } - - // Fill packet templates - fill_gbc_packet(ll_address, _latitude, _longitude, distanceA, distanceB, - angle); // TODO Check if GeoBroadcastArea lat/lon are identical to lat/lon of the Test System - fill_shb_packet(ll_address); - fill_tsb_packet(ll_address); - fill_uni_packet(ll_address); - fill_ls_reply(ll_address); - - // Register this object for AdapterControlPort - loggers::get_instance().log("geonetworking_layer::geonetworking_layer: Register %s/%p", p_type.c_str(), this); - registration::get_instance().add_item(p_type, this); - - // Add 4 leap seconds to convert to TAI (as Feb 2019) - base_time::get_instance().set_leap_delay_us(4 * 1000000); // TODO Set it as parameter -} // End of init_params - -void geonetworking_layer::sendMsg(const LibItsGeoNetworking__TestSystem::GeoNetworkingReq &p, params ¶ms) { - loggers::get_instance().log(">>> geonetworking_layer::sendMsg"); - - // Encode GeoNetworking PDU - OCTETSTRING data; - _codec.encode(p.msgOut(), data); - send_data(data, _params); -} - -void geonetworking_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> geonetworking_layer::send_data: ", data); - params.log(); - - if (_device_mode) { // Need to build a GN packet - params[params::certificate] = _params[params::certificate]; - params[params::hash] = _params[params::hash]; - params[params::signature] = _params[params::signature]; // TODO Should be removed - if (build_geonetworking_pdu(data, params) != 0) { - return; - } - } - if (_secured_mode) { // Add Security support - if (build_secured_pdu(data, params) != 0) { - return; - } - } - - // TODO To be removed - while (_sendData.try_lock() == FALSE) { - // not ready yet - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } // End of 'while' statement - send_to_all_layers(data, params); - _sendData.unlock(); - loggers::get_instance().log("<<< geonetworking_layer::send_data"); -} - -const TTCN_RAWdescriptor_t _intx_raw_ = {RAW_INTX, SG_NO, ORDER_MSB, ORDER_MSB, ORDER_LSB, ORDER_MSB, EXT_BIT_NO, ORDER_LSB, ORDER_LSB, - TOP_BIT_INHERITED, 0, 0, 0, 8, 0, NULL, -1, CharCoding::UNKNOWN}; -const TTCN_Typedescriptor_t _intx_descr_ = {"IntX", NULL, &_intx_raw_, NULL, NULL, NULL, NULL, NULL, TTCN_Typedescriptor_t::DONTCARE}; - -void geonetworking_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> geonetworking_layer::receive_data: ", data); - - // Check security mode - Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data; - LibItsGeoNetworking__TypesAndValues::BasicHeader basic_header; - decode_basic_header(data, basic_header); - if ((int)basic_header.nextHeader() == 2) { // Verify and extract the GeoNetworking Secured Packet as specified in ETSI EN 302 636-4-1 V1.3.1 (2017-08) - // Clause 9.6.1 Composition of the Basic Header - unsigned int basic_header_len = 4; // FIXME How to retrive the BasicHeader length basic_header.get_descriptor()->raw->fieldlength / 8; - loggers::get_instance().log("geonetworking_layer::receive_data: basic_header_len = %d", basic_header_len); - // Verify and extract the GeoNetworking Secured Packet as specified in ETSI EN 302 636-4-1 V1.3.1 (2017-08) Clause 9.4 GeoNetworking Secured Packet - OCTETSTRING unsecured_gn_payload; - OCTETSTRING secured_data = OCTETSTRING(data.lengthof() - basic_header_len, static_cast(data) + basic_header_len); - /////////////////// - // FIXME Check what to do with this! - if (*static_cast(secured_data) == 0x02) { // This is the old Security version format, discard it - /*loggers::get_instance().warning("geonetworking_layer::receive_data: Security error"); - if (_enable_security_checks) { - return; - } - INTEGER n; int r; - TTCN_Buffer buf(secured_data);*/ - loggers::get_instance().warning("geonetworking_layer::receive_data: Old security format, discard it anyway"); - return; /* - buf.increase_pos(1); // skip version - n.decode(_intx_descr_, buf, TTCN_EncDec::CT_RAW); - if(n > (int)buf.get_read_len()){ - loggers::get_instance().warning("geonetworking_layer::receive_data: Broken security headers"); - return; - } - buf.increase_pos((int)n); // skip headers - - // payload type - r = *buf.get_read_data(); - buf.increase_pos(1); - if(r != 3){ - n.decode(_intx_descr_, buf, TTCN_EncDec::CT_RAW); - //payload length - if(n > (int)buf.get_read_len()){ - loggers::get_instance().warning("geonetworking_layer::receive_data: Broken security payload"); - return; - } - unsecured_gn_payload = OCTETSTRING(n, buf.get_read_data()); - }*/ - } else if (*static_cast(secured_data) != 0x03) { - loggers::get_instance().warning("geonetworking_layer::receive_data: Security error, wrong protocol number, discard it anyway"); - if (_enable_security_checks) { - return; - } - return; - } else { - /////////////////// - if (security_services::get_instance().verify_and_extract_gn_payload(secured_data, _enable_security_checks, ieee_1609dot2_data, unsecured_gn_payload, - params) != 0) { - loggers::get_instance().warning("geonetworking_layer::receive_data: Security error"); - if (_enable_security_checks) { - return; - } - } - } - // Update data - loggers::get_instance().log_msg("geonetworking_layer::receive_data: Unsecured payload: ", unsecured_gn_payload); - data = OCTETSTRING(basic_header_len, static_cast(data)) + unsecured_gn_payload; - } - - // Decode the payload - loggers::get_instance().log_msg("geonetworking_layer::receive_data: Geonetworking payload to decode: ", data); - LibItsGeoNetworking__TestSystem::GeoNetworkingInd ind; - _codec.decode(data, ind.msgIn(), ¶ms); - if (ind.msgIn().is_bound()) { - // Update optional securedMsg field if required - if (ieee_1609dot2_data.is_bound()) { - ind.msgIn().gnPacket().securedMsg() = OPTIONAL(ieee_1609dot2_data); - } // else, nothing to do - // Update context - const LibItsGeoNetworking__TypesAndValues::LongPosVector * sopv = nullptr; - const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p = ind.msgIn().gnPacket().packet(); - const LibItsGeoNetworking__TypesAndValues::HeaderTST & htst = p.commonHeader().headerTST(); - if (p.extendedHeader().ispresent()) { // Update location table - const LibItsGeoNetworking__TypesAndValues::ExtendedHeader &ex = p.extendedHeader(); - if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_beaconHdr)) { // Receive a beacon - sopv = &ex.beaconHeader().srcPosVector(); - } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_tsbHdr)) { // Receive a topologicallyScopeBroadcast - if (ex.ischosen(LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_tsbHeader)) { - sopv = &ex.tsbHeader().srcPosVector(); - } else { - sopv = &ex.shbHeader().srcPosVector(); - } - } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_geoBroadcastHdr)) { - sopv = &ex.geoBroadcastHeader().srcPosVector(); - } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_lsHdr)) { // Receive a location service - if (ex.ischosen(LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_lsRequestHeader)) { // Receive a LocationService/LsRequest - sopv = &ex.lsRequestHeader().srcPosVector(); - // TODO Send LsReply if we are not in context of GN ATS in case of non GN test suite - if (_device_mode) { - // Update _ls_reply - ExtendedHeader *eh = static_cast(_ls_reply->gnPacket().packet().extendedHeader().get_opt_value()); - if (eh != nullptr) { - // Update sequence number - eh->lsReplyHeader().seqNumber() = _sequence_number++; - // Update destination - eh->lsReplyHeader().dstPosVector().gnAddr() = sopv->gnAddr(); - eh->lsReplyHeader().dstPosVector().latitude() = sopv->latitude(); - eh->lsReplyHeader().dstPosVector().longitude() = sopv->longitude(); - // Update timestamp - eh->lsReplyHeader().srcPosVector().timestamp__().set_long_long_val(base_time::get_instance().get_its_current_time_mod_ms()); - eh->lsReplyHeader().dstPosVector().timestamp__() = eh->lsReplyHeader().srcPosVector().timestamp__(); - - loggers::get_instance().log_msg("geonetworking_layer::receive_data: ", *_ls_reply); - - // send it - // Encode GeoNetworking PDU - OCTETSTRING os; - _codec.encode(*_ls_reply, os); - // Apply signature - if (_secured_mode) { - if (build_secured_pdu(data, _params) != 0) { - return; - } - } - // Send it - // TODO To be removed - while (_sendData.try_lock() == FALSE) { - // not ready yet - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } // End of 'while' statement - send_to_all_layers(os, params); - _sendData.unlock(); - } else { - loggers::get_instance().error("geonetworking_layer::send_data: Wrong cast"); - return; - } - } - } else { - sopv = &ex.lsReplyHeader().srcPosVector(); - } - } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_geoAnycastHdr)) { // Receive a GeoAnycast - sopv = &ex.geoAnycastHeader().srcPosVector(); - } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_geoUnicastHdr)) { - sopv = &ex.geoUnicastHeader().srcPosVector(); - } // else, nothing to do - loggers::get_instance().log("geonetworking_layer::receive_data: sopv is bound: %d", sopv->is_bound()); - if (sopv->is_bound()) { - const LibItsGeoNetworking__TypesAndValues::LongPosVector &lpv = *sopv; - _location_table.add_entry(lpv); - } - } - - // By default incoming beacons are filtered by the test adapter - if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_beaconHdr)) { - loggers::get_instance().log_msg("geonetworking_layer::receive_data: Pass beaconing filtering: ", sopv->gnAddr().mid()); - if (_pass_beacon_table.empty()) { // Discard beacon - loggers::get_instance().log("geonetworking_layer::receive_data: Pass beaconing table empty, discard it"); - return; - } else { // Check beacon filter for StartPassBeaconing/Stop - if (!_pass_beacon_table.has_entry(sopv->gnAddr().mid())) { // Discard beacon - loggers::get_instance().log_msg("geonetworking_layer::receive_data: Not in pass beaconing table, discard it", *sopv); - return; - } // else, continue - } - } // else, continue - } else { - // Inavlid GeoNetworking payload, discard it - loggers::get_instance().warning("geonetworking_layer::receive_data: Failed to decode payload, discard it"); - return; - } - - // Add lower layers parameters - // 1. Destination MAC address - params::const_iterator it = params.find(params::mac_dst); - if (it != params.cend()) { - loggers::get_instance().log("geonetworking_layer::receive_data: dst=%s", it->second.c_str()); - ind.macDestinationAddress() = str2oct(CHARSTRING(it->second.c_str())); - } else { - ind.macDestinationAddress() = str2oct(CHARSTRING(_params["mac_bc"].c_str())); - } - // 2. ssp - it = params.find(params::ssp); - if (it != params.cend()) { - loggers::get_instance().log("geonetworking_layer::receive_data: ssp=%s", it->second.c_str()); - ind.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); - } else { - ind.ssp().set_to_omit(); - } - // 3. its_aid - it = params.find(params::its_aid); - if (it != params.cend()) { - loggers::get_instance().log("geonetworking_layer::receive_data: its_aid=%s", it->second.c_str()); - ind.its__aid() = std::stoi(it->second.c_str()); - } else { - ind.its__aid().set_to_omit(); - } - - // Pass the GeoNetworking raw payload to the upper layers if any - it = params.find(params::gn_payload); - if (it != params.cend()) { - loggers::get_instance().log("geonetworking_layer::receive_data: gn_payload=%s", it->second.c_str()); - OCTETSTRING os(str2oct(CHARSTRING(it->second.c_str()))); - receive_to_all_layers(os, params); - } else { - loggers::get_instance().warning("geonetworking_layer::receive_data: No payload to pass to upper layers"); - } - - // Pass it to the ports - to_all_upper_ports(ind, params); -} - -OCTETSTRING geonetworking_layer::trigger_ac_event(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_to_hexa(">>> geonetworking_layer::trigger_ac_event: ", data); - - return int2oct(0, 2); -} // End of trigger_ac_event method - -void geonetworking_layer::start_beaconing() { - loggers::get_instance().log(">>> geonetworking_layer::start_beaconing"); - // loggers::get_instance().log_msg("geonetworking_layer::start_beaconing: _beacon=", *_beacon); - - // Establish handler for timer signal - loggers::get_instance().log("geonetworking_layer::start_beaconing: Establishing handler for signal %d\n", _signal_id); - _sa.sa_flags = SA_SIGINFO; - _sa.sa_sigaction = timer_irq_sigalrm_handler; - sigemptyset(&_sa.sa_mask); - if (sigaction(_signal_id, &_sa, nullptr) == -1) { - loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigaction failure: %d", errno); - } - // Block timer signal temporarily - loggers::get_instance().log("geonetworking_layer::start_beaconing: Blocking signal %d\n", _signal_id); - sigemptyset(&_mask); - sigaddset(&_mask, _signal_id); - if (sigprocmask(SIG_SETMASK, &_mask, nullptr) == -1) { - loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigprocmask failure: %d", errno); - } - // Create the timer - _sev.sigev_notify = SIGEV_SIGNAL; - _sev.sigev_signo = _signal_id; // Use signal alarm - _sev.sigev_value.sival_ptr = this; // The geonetworking_layer object address - if (timer_create(CLOCK_REALTIME, &_sev, &_timerid) == -1) { - loggers::get_instance().error("geonetworking_layer::start_beaconing: Timer failure: %d", errno); - } - loggers::get_instance().log("geonetworking_layer::start_beaconing: timer ID is 0x%x\n", (long)_timerid); - // Start the timer - unsigned int expiry = 1000; // Default expiry time 1000ms - params::const_iterator i = _params.find("expiry"); - if (i != _params.cend()) { - expiry = static_cast(std::strtoul(i->second.c_str(), nullptr, 10)); - } - _freq_nanosecs = expiry * 1000000; - _its.it_value.tv_sec = _freq_nanosecs / 1000000000; - _its.it_value.tv_nsec = _freq_nanosecs % 1000000000; - _its.it_interval.tv_sec = _its.it_value.tv_sec; - _its.it_interval.tv_nsec = _its.it_value.tv_nsec; - if (timer_settime(_timerid, 0, &_its, nullptr) == -1) { - loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigprocmask failure: %d", errno); - } - // Unlock the timer signal, so that timer notification can be delivered - loggers::get_instance().log("geonetworking_layer::start_beaconing: Unblocking signal %d\n", _signal_id); - if (sigprocmask(SIG_UNBLOCK, &_mask, nullptr) == -1) { - loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigprocmask failure: %d", errno); - } -} // End of start_beaconing method - -void geonetworking_layer::start_beaconing(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &p_beacon) { - loggers::get_instance().log_msg(">>> geonetworking_layer::start_beaconing", p_beacon); - - // Initialize the beacon - if (_beacon != nullptr) { - delete _beacon; - } - _beacon = new LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu(p_beacon); - - start_beaconing(); // TODO Refined adding a boolean return code -} // End of start_beaconing method - -void geonetworking_layer::stop_beaconing() { - loggers::get_instance().log(">>> geonetworking_layer::stop_beaconing"); - - // Block timer signal temporarily - loggers::get_instance().log("geonetworking_layer::stop_beaconing: Blocking signal %d\n", _signal_id); - sigemptyset(&_mask); - sigaddset(&_mask, _signal_id); - if (sigprocmask(SIG_SETMASK, &_mask, nullptr) == -1) { - loggers::get_instance().error("geonetworking_layer::stop_beaconing: Sigprocmask failure: %d", errno); - } - timer_delete(_timerid); - _timerid = 0; -} // End of stop_beaconing method - -void geonetworking_layer::send_beacon() { - loggers::get_instance().log(">>> geonetworking_layer::send_beacon"); - - ExtendedHeader *eh = static_cast(_beacon->gnPacket().packet().extendedHeader().get_opt_value()); - if (eh == nullptr) { - loggers::get_instance().error("geonetworking_layer::send_beacon: Wrong cast"); - } - // Update timestamp - eh->beaconHeader().srcPosVector().timestamp__().set_long_long_val((unsigned int)base_time::get_instance().get_its_current_time_mod_ms()); - // loggers::get_instance().log_msg("geonetworking_layer::send_beacon: ", *_beacon); - // Encode message using TITAN because of payload in omited - TTCN_Buffer encoding_buffer; - _beacon->encode(*(_beacon->get_descriptor()), encoding_buffer, TTCN_EncDec::CT_RAW); - OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); - params params(_params); - if (_secured_mode) { // Apply Security - if (build_secured_pdu(data, _params) != 0) { - return; - } - } - // Send it - // TODO To be removed - while (_sendData.try_lock() == FALSE) { - // not ready yet - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } // End of 'while' statement - send_to_all_layers(data, params); - _sendData.unlock(); - - // loggers::get_instance().log("<<< geonetworking_layer::send_beacon"); -} // End of send_beacon method - -void geonetworking_layer::start_pass_beaconing(const LibItsGeoNetworking__TypesAndValues::BeaconHeader &p_beacon) { - loggers::get_instance().log_msg(">>> geonetworking_layer::start_pass_beaconing", p_beacon); - - const LibItsGeoNetworking__TypesAndValues::LongPosVector &lpv = p_beacon.srcPosVector(); - if (!_pass_beacon_table.has_entry(lpv.gnAddr().mid())) { - _pass_beacon_table.add_entry(lpv); - } // TODO Refined adding a boolean return code -} // End of start_pass_beaconing method - -void geonetworking_layer::stop_pass_beaconing() { - loggers::get_instance().log(">>> geonetworking_layer::stop_pass_beaconing"); - - _pass_beacon_table.reset(); -} // End of stop_pass_beaconing method - -int geonetworking_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { - loggers::get_instance().log(">>> geonetworking_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); - - loggers::get_instance().log("geonetworking_layer::enable_secured_mode: _secured_mode = %x", _secured_mode); - if (!_secured_mode) { - loggers::get_instance().log("geonetworking_layer::enable_secured_mode: Setup secured mode"); - _secured_mode = true; - setup_secured_mode(); - } - _enable_security_checks = p_enforce_security; - params::const_iterator it = _params.find(params::certificate); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("certificate"), p_certificate_id)); - } else { - _params[params::certificate] = p_certificate_id; - } - loggers::get_instance().log("geonetworking_layer::enable_secured_mode: Certificate to be used: '%s'", _params[params::certificate].c_str()); - - return 0; -} - -int geonetworking_layer::disable_secured_mode() { - loggers::get_instance().log(">>> geonetworking_layer::disable_secured_mode"); - _secured_mode = false; - _enable_security_checks = false; - return 0; -} - -const LongPosVector *geonetworking_layer::get_lpv(const GN__Address &p_gn_address) { - loggers::get_instance().log_msg(">>> geonetworking_layer::get_lpv", p_gn_address); - - const LongPosVector *lpv = nullptr; - if (_location_table.has_entry(p_gn_address.mid())) { - lpv = _location_table.get_entry(p_gn_address.mid()); - } - return lpv; -} // End of get_lpv - -const LibItsGeoNetworking__TypesAndValues::BasicHeader geonetworking_layer::fill_basic_header() const { - return LibItsGeoNetworking__TypesAndValues::BasicHeader(1, // GeoNetworking version - BasicNextHeader(BasicNextHeader::e__commonHeader), 0, Lifetime(4, LtBase(LtBase::e__50ms)), 1); -} - -void geonetworking_layer::fill_beacon(const OCTETSTRING &p_ll_address, const INTEGER p_station_type, const INTEGER p_country, const INTEGER type_of_address) { - _beacon = new GeoNetworkingPdu(); - HeaderTST h; - h.beaconHdr() = BeaconHeaderType(HeaderType(HeaderType::e__beacon), 0); - ExtendedHeader eh; - eh.beaconHeader() = - BeaconHeader(LongPosVector(GN__Address(TypeOfAddress((TypeOfAddress)type_of_address), StationType((StationType)p_station_type), p_country, p_ll_address), 0, - _latitude, _longitude, int2bit(0, 1), 0, 0)); - _beacon->basicHeader() = fill_basic_header(); - _beacon->gnPacket().packet() = - GnNonSecuredPacket(CommonHeader(NextHeader(NextHeader::e__any), 0, h, - TrafficClass(SCF(SCF::e__scfEnabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), int2bit(0, 8), 0, 1, 0), - OPTIONAL(eh), OPTIONAL()); - _beacon->gnPacket().packet().payload().set_to_omit(); - _beacon->gnPacket().securedMsg().set_to_omit(); - // loggers::get_instance().log_msg("geonetworking_layer::fill_beacon: beacon value: ", *_beacon); -} // End of fill_beacon method - -void geonetworking_layer::fill_gbc_packet(const OCTETSTRING &p_ll_address, const INTEGER &p_geoAreaPosLatitude, const INTEGER &p_geoAreaPosLongitude, - const INTEGER &p_distanceA, const INTEGER &p_distanceB, const INTEGER &p_angle) { - _gbc_packet = new GeoNetworkingPdu(); - HeaderTST h; - h.geoBroadcastHdr() = - GeoBroadcastHeaderType(HeaderType(HeaderType::e__geoBroadcast), HeaderSubTypeGeoBroadcast(HeaderSubTypeGeoBroadcast::e__geoBroadcastElip)); - ExtendedHeader eh; - eh.geoBroadcastHeader() = GeoAnycastHeader( // GeoBradcastHeader is identical as GeoAnycastHeader - 0, 0, - LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude, _longitude, int2bit(1, 1), // PAI - 0, 0), - p_geoAreaPosLatitude, p_geoAreaPosLongitude, p_distanceA, p_distanceB, p_angle, 0); - _gbc_packet->basicHeader() = fill_basic_header(); - _gbc_packet->gnPacket().packet() = GnNonSecuredPacket( - CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), - int2bit(128, 8), // Mobile stationnary flag set - 0, 5, 0), - OPTIONAL(eh), OPTIONAL()); - _gbc_packet->gnPacket().packet().payload().set_to_omit(); - _gbc_packet->gnPacket().securedMsg().set_to_omit(); - // loggers::get_instance().log_msg("geonetworking_layer::fill_gbc_packet: packet value: ", *_gbc_packet); -} // End of fill_gbc_packet method - -void geonetworking_layer::fill_shb_packet(const OCTETSTRING &p_ll_address) { - _shb_packet = new GeoNetworkingPdu(); - HeaderTST h; - h.tsbHdr() = TsbHeaderType(HeaderType(HeaderType::e__topologicallyScopedBroadcast), HeaderSubTypeTSB(HeaderSubTypeTSB::e__singleHop)); - ExtendedHeader eh; - eh.shbHeader() = SHBHeader(LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude, _longitude, int2bit(1, 1), // PAI - 0, 0), - 0); - _shb_packet->basicHeader() = fill_basic_header(); - _shb_packet->gnPacket().packet() = GnNonSecuredPacket( - CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), - int2bit(128, 8), // Mobile stationnary flag set - 0, 1, 0), - OPTIONAL(eh), OPTIONAL()); - _shb_packet->gnPacket().packet().payload().set_to_omit(); - _shb_packet->gnPacket().securedMsg().set_to_omit(); - // loggers::get_instance().log_msg("geonetworking_layer::fill_shb_packet: packet value: ", *_shb_packet); -} // End of fill_shb_packet method - -void geonetworking_layer::fill_tsb_packet(const OCTETSTRING &p_ll_address, const int p_hop_number, const int p_max_hop_limit) { - _tsb_packet = new GeoNetworkingPdu(); - HeaderTST h; - h.tsbHdr() = TsbHeaderType(HeaderType(HeaderType::e__topologicallyScopedBroadcast), HeaderSubTypeTSB(HeaderSubTypeTSB::e__multiHop)); - ExtendedHeader eh; - eh.tsbHeader() = TSBHeader(0, 0, - LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude, _longitude, int2bit(1, 1), // PAI - 0, 0)); - _tsb_packet->basicHeader() = fill_basic_header(); - _tsb_packet->gnPacket().packet() = GnNonSecuredPacket( - CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), - int2bit(128, 8), // Mobile stationnary flag set - 0, p_max_hop_limit, 0), - OPTIONAL(eh), OPTIONAL()); - _tsb_packet->gnPacket().packet().payload().set_to_omit(); - _tsb_packet->gnPacket().securedMsg().set_to_omit(); - // loggers::get_instance().log_msg("geonetworking_layer::fill_tsb_packet: packet value: ", *_tsb_packet); -} // End of fill_tsb_packet method - -void geonetworking_layer::fill_uni_packet(const OCTETSTRING &p_ll_address, const int p_hop_number, const int p_max_hop_limit) { - _uni_packet = new GeoNetworkingPdu(); - HeaderTST h; - h.geoUnicastHdr() = GeoUnicastHeaderType(HeaderType(HeaderType::e__geoUnicast), 0); - ExtendedHeader eh; - eh.geoUnicastHeader() = GeoUnicastHeader(0, 0, - LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude, _longitude, int2bit(1, 1), // PAI - 0, 0), - ShortPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude + 100, _longitude + 100)); - _uni_packet->basicHeader() = fill_basic_header(); - _uni_packet->gnPacket().packet() = GnNonSecuredPacket( - CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), - int2bit(128, 8), // Mobile stationnary flag set - 0, p_max_hop_limit, 0), - OPTIONAL(eh), OPTIONAL()); - _uni_packet->gnPacket().packet().payload().set_to_omit(); - _uni_packet->gnPacket().securedMsg().set_to_omit(); - // loggers::get_instance().log_msg("geonetworking_layer::fill_uni_packet: packet value: ", *_uni_packet); -} // End of fill_uni_packet method - -void geonetworking_layer::fill_ls_reply(const OCTETSTRING &p_ll_address) { - _ls_reply = new GeoNetworkingPdu(); - HeaderTST h; - h.lsHdr() = LsHeaderType(HeaderType(HeaderType::e__locationService), HeaderSubTypeLs(HeaderSubTypeLs::e__lsReply)); - ExtendedHeader eh; - eh.lsReplyHeader() = LSReplyHeader(0, 0, - LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude, _longitude, int2bit(1, 1), // PAI - 0, 0), - ShortPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params - StationType(StationType::e__passengerCar), // TODO Use params - 33, p_ll_address), - 0, _latitude, _longitude)); - _ls_reply->basicHeader() = fill_basic_header(); - _ls_reply->gnPacket().packet() = GnNonSecuredPacket(CommonHeader(NextHeader(NextHeader::e__any), 0, h, - TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), - int2bit(128, 8), // Mobile stationnary flag set - 0, 5, 0), - OPTIONAL(eh), OPTIONAL()); - _ls_reply->gnPacket().packet().payload().set_to_omit(); - _ls_reply->gnPacket().securedMsg().set_to_omit(); - // loggers::get_instance().log_msg("geonetworking_layer::fill_ls_reply: packet value: ", *_ls_reply); -} // End of fill_ls_reply method - -void geonetworking_layer::timer_irq_sigalrm_handler(int p_signal, siginfo_t *p_signal_info, void *p_uc) { - // loggers::get_instance().log(">>> geonetworking_layer::timer_irq_sigalrm_handler: Caught signal %d", p_signal); - - static_cast(p_signal_info->si_value.sival_ptr)->send_beacon(); -} // End of method timer_irq_sigalrm_handler - -int geonetworking_layer::build_geonetworking_pdu(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> geonetworking_layer::build_geonetworking_pdu"); - // params.log(); - - std::string next_header; - params::const_iterator it = params.find(params::next_header); - if (it != params.cend()) { - next_header = it->second.c_str(); - } - std::string header_type; - it = params.find(params::header_type); - if (it != params.cend()) { - header_type = it->second.c_str(); - } - std::string header_sub_type; - it = params.find(params::header_sub_type); - if (it != params.cend()) { - header_sub_type = it->second.c_str(); - } - loggers::get_instance().log("geonetworking_layer::build_geonetworking_pdu: %s, %s, %s", next_header.c_str(), header_type.c_str(), header_sub_type.c_str()); - - if (header_type.compare("tsb") == 0) { - if (header_sub_type.compare("sh") == 0) { // Use SHB - ExtendedHeader *eh = static_cast(_shb_packet->gnPacket().packet().extendedHeader().get_opt_value()); - if (eh == nullptr) { - loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); - return -1; - } - // Update NextHeader - it = params.find(params::next_header); - if (next_header.compare("btpB") == 0) { - _shb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; - } else { // Default btp is btpA - _shb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; - } - // Update payload - _shb_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); - _shb_packet->gnPacket().packet().payload() = OPTIONAL(data); - // Update timestamp - eh->shbHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); - - loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: shb: ", *_shb_packet); - // Encode GeoNetworking PDU - OCTETSTRING os; - _codec.encode(*_shb_packet, os); - data = os; - } else { // Use TSB - ExtendedHeader *eh = static_cast(_tsb_packet->gnPacket().packet().extendedHeader().get_opt_value()); - if (eh == nullptr) { - loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); - return -1; - } - // Update sequence number - eh->tsbHeader().seqNumber() = _sequence_number++; - // Update NextHeader - it = params.find(params::next_header); - if (next_header.compare("btpB") == 0) { - _tsb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; - } else { // Default btp is btpA - _tsb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; - } - // Update payload - _tsb_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); - _tsb_packet->gnPacket().packet().payload() = OPTIONAL(data); - // Update timestamp - eh->tsbHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); - - loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: tsb: ", *_tsb_packet); - // Encode GeoNetworking PDU - OCTETSTRING os; - _codec.encode(*_tsb_packet, os); - data = os; - } - } else if (header_type.compare("uni") == 0) { - ExtendedHeader *eh = static_cast(_uni_packet->gnPacket().packet().extendedHeader().get_opt_value()); - if (eh == nullptr) { - loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); - return -1; - } - // Update NextHeader - it = params.find(params::next_header); - if (next_header.compare("btpB") == 0) { - _uni_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; - } else { // Default btp is btpA - _uni_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; - } - // Update sequence number - eh->geoUnicastHeader().seqNumber() = _sequence_number++; - // Update payload - _uni_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); - _uni_packet->gnPacket().packet().payload() = OPTIONAL(data); - // Update timestamp - eh->geoUnicastHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); - - loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: uni: ", *_uni_packet); - - // Encode GeoNetworking PDU - OCTETSTRING os; - _codec.encode(*_uni_packet, os); - data = os; - } else { // TODO To be continued - // Default: Use GBC - ExtendedHeader *eh = static_cast(_gbc_packet->gnPacket().packet().extendedHeader().get_opt_value()); - if (eh == nullptr) { - loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); - return -1; - } - // Update NextHeader - it = params.find(params::next_header); - if (next_header.compare("btpB") == 0) { - _gbc_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; - } else { // Default btp is btpA - _gbc_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; - } - // Update sequence number - eh->geoBroadcastHeader().seqNumber() = _sequence_number++; - // Update payload - _gbc_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); - _gbc_packet->gnPacket().packet().payload() = OPTIONAL(data); - // Update timestamp - eh->geoBroadcastHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); - - loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: gbc: ", *_gbc_packet); - - // Encode GeoNetworking PDU - OCTETSTRING os; - _codec.encode(*_gbc_packet, os); - data = os; - } - - return 0; -} - -int geonetworking_layer::build_secured_pdu(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> geonetworking_layer::build_secured_pdu: ", data); - // params.log(); - - LibItsGeoNetworking__TypesAndValues::BasicHeader basic_header; - decode_basic_header(data, basic_header); - if (basic_header.nextHeader() == BasicNextHeader::e__securedPacket) { // Already secured (ATS Security test suite/f_sendSecuredGn/Cam/Denm TTCN-3 functions - // Leave data unchanged - loggers::get_instance().log_msg("<<< geonetworking_layer::build_secured_pdu: Leave data unchanged: ", data); - return 0; - } - // Update security mode - unsigned int basic_header_len = 4; // FIXME How to retrive the BasicHeader length basic_header.get_descriptor()->raw->fieldlength / 8; - loggers::get_instance().log("geonetworking_layer::build_secured_pdu: basic_header_len = %d", basic_header_len); - basic_header.nextHeader() = BasicNextHeader::e__securedPacket; - OCTETSTRING unsecured_gn_payload = OCTETSTRING(data.lengthof() - basic_header_len, static_cast(data) + basic_header_len); - OCTETSTRING secured_gn_payload; - if (security_services::get_instance().secure_gn_payload(unsecured_gn_payload, secured_gn_payload, params) != 0) { - loggers::get_instance().warning("geonetworking_layer::build_secured_pdu: failed to build secured pdu"); - return -1; - } - - // Encode the basic header - // loggers::get_instance().log_msg("geonetworking_layer::build_secured_pdu: New basic_header = ", basic_header); - RAW_enc_tr_pos rp; - rp.level = 0; - rp.pos = NULL; - RAW_enc_tree enc_tree(FALSE, NULL, &rp, 1, basic_header.get_descriptor()->raw); - basic_header.RAW_encode(*basic_header.get_descriptor(), enc_tree); - TTCN_Buffer encoding_buffer; - enc_tree.put_to_buf(encoding_buffer); - // Copy result - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()) + secured_gn_payload; - loggers::get_instance().log_msg("geonetworking_layer::build_secured_pdu: Secured pdu = ", data); - - return 0; -} - -int geonetworking_layer::decode_basic_header(const OCTETSTRING &p_data, LibItsGeoNetworking__TypesAndValues::BasicHeader &p_basic_header) { - // loggers::get_instance().log_msg(">>> geonetworking_layer::decode_basic_header: ", p_data); - - // Update security mode - OCTETSTRING bh = - OCTETSTRING(4, static_cast(p_data)); // Extract the basic header as specified in ETSI EN 302 636-4-1 V1.3.1 (2017-08) Clause 9.6 - // loggers::get_instance().log_msg("geonetworking_layer::decode_basic_header: bh: ", bh); - TTCN_Buffer decoding_buffer(bh); - p_basic_header.RAW_decode(*p_basic_header.get_descriptor(), decoding_buffer, decoding_buffer.get_len() * 8, raw_order_t::ORDER_MSB); - // loggers::get_instance().log_msg("geonetworking_layer::decode_basic_header: ", p_basic_header); - - return 0; -} - -int geonetworking_layer::setup_secured_mode() { - loggers::get_instance().log(">>> geonetworking_layer::setup_secured_mode"); - - loggers::get_instance().log("geonetworking_layer::setup_secured_mode: GN Layer address = %p", this); - - params::const_iterator it = _params.find(params::certificate); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("certificate"), "CERT_TS_A_AT")); - } - it = _params.find(params::sec_db_path); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("sec_db_path"), "")); - } - it = _params.find(params::hash); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("hash"), "SHA-256")); - } - it = _params.find(params::signature); // TODO Should be removed - if (it == _params.cend()) { - _params.insert(std::pair(std::string("signature"), "NISTP-256")); - } - // Set up security services even if secured_mode is set to 0. Later, we can receive an AcEnableSecurity request, the sertificate caching will be ready to go - security_services::get_instance().setup(_params); - security_services::get_instance().set_position(_latitude, _longitude); - - return 0; -} - -geonetworking_layer_factory geonetworking_layer_factory::_f; +#include +#include +#include +#include + +#include "geonetworking_types.hh" + +#include "geonetworking_layer_factory.hh" + +#include "loggers.hh" + +#include "security_services.hh" + +#include "base_time.hh" + +#include "registration.hh" + +#include "converter.hh" + +using namespace LibItsGeoNetworking__TypesAndValues; + +geonetworking_layer::geonetworking_layer(const std::string &p_type, const std::string &p_param) + : t_layer(p_type), _params(), _codec(), _beacon(nullptr), _gbc_packet(nullptr), _shb_packet(nullptr), + _tsb_packet(nullptr), _uni_packet(nullptr), _ls_reply(nullptr), _location_table(), + _pass_beacon_table(), _device_mode{false}, _secured_mode{false}, _encrypted_mode{false}, _enable_security_checks{false}, + _sendData(), _timerid{0}, _sev{0}, _its{0}, _freq_nanosecs(0), _mask{0}, _sa{0}, _sequence_number{0}, _latitude{0}, _longitude{0} { + loggers::get_instance().log(">>> geonetworking_layer::geonetworking_layer: %s, %s", to_string().c_str(), p_param.c_str()); + + init(p_type, p_param); +} // End of constructor + +geonetworking_layer::~geonetworking_layer() { + loggers::get_instance().log(">>> geonetworking_layer::~geonetworking_layer"); + + if (_timerid != 0) { + timer_delete(_timerid); + } + if (_beacon != nullptr) { + delete _beacon; + } + if (_gbc_packet != nullptr) { + delete _gbc_packet; + } + if (_shb_packet != nullptr) { + delete _shb_packet; + } + if (_tsb_packet != nullptr) { + delete _tsb_packet; + } + if (_uni_packet != nullptr) { + delete _uni_packet; + } + if (_ls_reply != nullptr) { + delete _ls_reply; + } +} // End of destructor + +void geonetworking_layer::init(const std::string &p_type, const std::string &p_param) { + loggers::get_instance().log(">>> geonetworking_layer::init: %s, %s", to_string().c_str(), p_param.c_str()); + + // Setup parameters + params::convert(_params, p_param); + // Sanity checks + params::const_iterator it = _params.find(params::latitude); + if (it != _params.cend()) { + _latitude = converter::get_instance().string_to_int(it->second); + } + it = _params.find(params::longitude); + if (it != _params.cend()) { + _longitude = converter::get_instance().string_to_int(it->second); + } + OCTETSTRING ll_address; + it = _params.find(params::ll_address); + if (it != _params.cend()) { + ll_address = str2oct(CHARSTRING(it->second.c_str())); + } + INTEGER distanceA = 1000; // 1km + it = _params.find(params::distanceA); + if (it != _params.cend()) { + distanceA = converter::get_instance().string_to_int(it->second); + } + INTEGER distanceB = 1000; // 1Km + it = _params.find(params::distanceB); + if (it != _params.cend()) { + distanceB = converter::get_instance().string_to_int(it->second); + } + INTEGER angle = 0; + it = _params.find(params::angle); + if (it != _params.cend()) { + angle = converter::get_instance().string_to_int(it->second); + } + INTEGER station_type = 5; // passangerCar + it = _params.find(params::station_type); + if (it != _params.cend()) { + station_type = converter::get_instance().string_to_int(it->second); + } + INTEGER country = 0; + it = _params.find(params::country); + if (it != _params.cend()) { + country = converter::get_instance().string_to_int(it->second); + } + INTEGER type_of_address = 1; // Manual + it = _params.find(params::type_of_address); + if (it != _params.cend()) { + type_of_address = converter::get_instance().string_to_int(it->second); + } + + it = _params.find(params::device_mode); + if (it != _params.cend()) { + _device_mode = (1 == converter::get_instance().string_to_int(it->second)); + } + it = _params.find(params::secured_mode); + if (it != _params.cend()) { + _secured_mode = (1 == converter::get_instance().string_to_int(it->second)); + } else { + _params.insert(std::pair(std::string("secured_mode"), "0")); + } + it = _params.find(params::encrypted_mode); + if (it != _params.cend()) { + _encrypted_mode = (1 == converter::get_instance().string_to_int(it->second)); + } else { + _params.insert(std::pair(std::string("encrypted_mode"), "0")); + } + it = _params.find(params::enable_security_checks); + if (it != _params.cend()) { + _enable_security_checks = (1 == converter::get_instance().string_to_int(it->second)); + } + + // Add broadcast address if needed + it = _params.find(params::its_aid); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("its_aid"), "141")); + } + it = _params.find(params::mac_bc); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("mac_bc"), "FFFFFFFFFFFF")); + } + + // Set up default security parameters value + if (_secured_mode || _encrypted_mode) { + loggers::get_instance().log("geonetworking_layer::geonetworking_layer: Setup secured mode"); + setup_secured_mode(); + } + + // Automatic beaconing mode + fill_beacon(ll_address, station_type, country, type_of_address); + params::const_iterator i = _params.find(params::beaconing); + if ((i != _params.cend()) && (i->second.compare("1") == 0)) { // Immediate beaconing was requested + // Prepare beaconing operation + start_beaconing(); + } + + // Fill packet templates + fill_gbc_packet(ll_address, _latitude, _longitude, distanceA, distanceB, + angle); // TODO Check if GeoBroadcastArea lat/lon are identical to lat/lon of the Test System + fill_shb_packet(ll_address); + fill_tsb_packet(ll_address); + fill_uni_packet(ll_address); + fill_ls_reply(ll_address); + + // Register this object for AdapterControlPort + loggers::get_instance().log("geonetworking_layer::geonetworking_layer: Register %s/%p", p_type.c_str(), this); + registration::get_instance().add_item(p_type, this); + + // Add 4 leap seconds to convert to TAI (as Feb 2019) + base_time::get_instance().set_leap_delay_us(4 * 1000000); // TODO Set it as parameter +} // End of init_params + +void geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingReq &p, params ¶ms) { + loggers::get_instance().log(">>> geonetworking_layer::sendMsg"); + + // Encode GeoNetworking PDU + OCTETSTRING data; + _codec.encode(p.msgOut(), data); + send_data(data, _params); +} + +void geonetworking_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> geonetworking_layer::send_data: ", data); + params.log(); + + if (_device_mode) { // Need to build a GN packet + params[params::certificate] = _params[params::certificate]; + params[params::hash] = _params[params::hash]; + params[params::signature] = _params[params::signature]; // TODO Should be removed + if (build_geonetworking_pdu(data, params) != 0) { + return; + } + } + if (_secured_mode) { // Add Security support + if (build_secured_pdu(data, params) != 0) { + return; + } + } + + // TODO To be removed + while (_sendData.try_lock() == FALSE) { + // not ready yet + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } // End of 'while' statement + send_to_all_layers(data, params); + _sendData.unlock(); + loggers::get_instance().log("<<< geonetworking_layer::send_data"); +} + +const TTCN_RAWdescriptor_t _intx_raw_ = {RAW_INTX, SG_NO, ORDER_MSB, ORDER_MSB, ORDER_LSB, ORDER_MSB, EXT_BIT_NO, ORDER_LSB, ORDER_LSB, + TOP_BIT_INHERITED, 0, 0, 0, 8, 0, NULL, -1, CharCoding::UNKNOWN}; +const TTCN_Typedescriptor_t _intx_descr_ = {"IntX", NULL, &_intx_raw_, NULL, NULL, NULL, NULL, NULL, TTCN_Typedescriptor_t::DONTCARE}; + +void geonetworking_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> geonetworking_layer::receive_data: ", data); + + // Check security mode + Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data; + LibItsGeoNetworking__TypesAndValues::BasicHeader basic_header; + decode_basic_header(data, basic_header); + if ((int)basic_header.nextHeader() == 2) { // Verify and extract the GeoNetworking Secured Packet as specified in ETSI EN 302 636-4-1 V1.3.1 (2017-08) + // Clause 9.6.1 Composition of the Basic Header + unsigned int basic_header_len = 4; // FIXME How to retrive the BasicHeader length basic_header.get_descriptor()->raw->fieldlength / 8; + loggers::get_instance().log("geonetworking_layer::receive_data: basic_header_len = %d", basic_header_len); + // Verify and extract the GeoNetworking Secured Packet as specified in ETSI EN 302 636-4-1 V1.3.1 (2017-08) Clause 9.4 GeoNetworking Secured Packet + OCTETSTRING unsecured_gn_payload; + OCTETSTRING secured_data = OCTETSTRING(data.lengthof() - basic_header_len, static_cast(data) + basic_header_len); + /////////////////// + // FIXME Check what to do with this! + if (*static_cast(secured_data) == 0x02) { // This is the old Security version format, discard it + /*loggers::get_instance().warning("geonetworking_layer::receive_data: Security error"); + if (_enable_security_checks) { + return; + } + INTEGER n; int r; + TTCN_Buffer buf(secured_data);*/ + loggers::get_instance().warning("geonetworking_layer::receive_data: Old security format, discard it anyway"); + return; /* + buf.increase_pos(1); // skip version + n.decode(_intx_descr_, buf, TTCN_EncDec::CT_RAW); + if(n > (int)buf.get_read_len()){ + loggers::get_instance().warning("geonetworking_layer::receive_data: Broken security headers"); + return; + } + buf.increase_pos((int)n); // skip headers + + // payload type + r = *buf.get_read_data(); + buf.increase_pos(1); + if(r != 3){ + n.decode(_intx_descr_, buf, TTCN_EncDec::CT_RAW); + //payload length + if(n > (int)buf.get_read_len()){ + loggers::get_instance().warning("geonetworking_layer::receive_data: Broken security payload"); + return; + } + unsecured_gn_payload = OCTETSTRING(n, buf.get_read_data()); + }*/ + } else if (*static_cast(secured_data) != 0x03) { + loggers::get_instance().warning("geonetworking_layer::receive_data: Security error, wrong protocol number, discard it anyway"); + if (_enable_security_checks) { + return; + } + return; + } else { + /////////////////// + if (security_services::get_instance().verify_and_extract_gn_payload(secured_data, _enable_security_checks, ieee_1609dot2_data, unsecured_gn_payload, + params) != 0) { + loggers::get_instance().warning("geonetworking_layer::receive_data: Security error"); + if (_enable_security_checks) { + return; + } + } + } + // Update data + loggers::get_instance().log_msg("geonetworking_layer::receive_data: Unsecured payload: ", unsecured_gn_payload); + data = OCTETSTRING(basic_header_len, static_cast(data)) + unsecured_gn_payload; + } + + // Decode the payload + loggers::get_instance().log_msg("geonetworking_layer::receive_data: Geonetworking payload to decode: ", data); + LibItsGeoNetworking__TypesAndValues::GeoNetworkingInd ind; + _codec.decode(data, ind.msgIn(), ¶ms); + if (ind.msgIn().is_bound()) { + // Update optional securedMsg field if required + if (ieee_1609dot2_data.is_bound()) { + ind.msgIn().gnPacket().securedMsg() = OPTIONAL(ieee_1609dot2_data); + } // else, nothing to do + // Update context + const LibItsGeoNetworking__TypesAndValues::LongPosVector * sopv = nullptr; + const LibItsGeoNetworking__TypesAndValues::GnNonSecuredPacket &p = ind.msgIn().gnPacket().packet(); + const LibItsGeoNetworking__TypesAndValues::HeaderTST & htst = p.commonHeader().headerTST(); + if (p.extendedHeader().ispresent()) { // Update location table + const LibItsGeoNetworking__TypesAndValues::ExtendedHeader &ex = p.extendedHeader(); + if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_beaconHdr)) { // Receive a beacon + sopv = &ex.beaconHeader().srcPosVector(); + } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_tsbHdr)) { // Receive a topologicallyScopeBroadcast + if (ex.ischosen(LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_tsbHeader)) { + sopv = &ex.tsbHeader().srcPosVector(); + } else { + sopv = &ex.shbHeader().srcPosVector(); + } + } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_geoBroadcastHdr)) { + sopv = &ex.geoBroadcastHeader().srcPosVector(); + } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_lsHdr)) { // Receive a location service + if (ex.ischosen(LibItsGeoNetworking__TypesAndValues::ExtendedHeader::ALT_lsRequestHeader)) { // Receive a LocationService/LsRequest + sopv = &ex.lsRequestHeader().srcPosVector(); + // TODO Send LsReply if we are not in context of GN ATS in case of non GN test suite + if (_device_mode) { + // Update _ls_reply + ExtendedHeader *eh = static_cast(_ls_reply->gnPacket().packet().extendedHeader().get_opt_value()); + if (eh != nullptr) { + // Update sequence number + eh->lsReplyHeader().seqNumber() = _sequence_number++; + // Update destination + eh->lsReplyHeader().dstPosVector().gnAddr() = sopv->gnAddr(); + eh->lsReplyHeader().dstPosVector().latitude() = sopv->latitude(); + eh->lsReplyHeader().dstPosVector().longitude() = sopv->longitude(); + // Update timestamp + eh->lsReplyHeader().srcPosVector().timestamp__().set_long_long_val(base_time::get_instance().get_its_current_time_mod_ms()); + eh->lsReplyHeader().dstPosVector().timestamp__() = eh->lsReplyHeader().srcPosVector().timestamp__(); + + loggers::get_instance().log_msg("geonetworking_layer::receive_data: ", *_ls_reply); + + // send it + // Encode GeoNetworking PDU + OCTETSTRING os; + _codec.encode(*_ls_reply, os); + // Apply signature + if (_secured_mode) { + if (build_secured_pdu(data, _params) != 0) { + return; + } + } + // Send it + // TODO To be removed + while (_sendData.try_lock() == FALSE) { + // not ready yet + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } // End of 'while' statement + send_to_all_layers(os, params); + _sendData.unlock(); + } else { + loggers::get_instance().error("geonetworking_layer::send_data: Wrong cast"); + return; + } + } + } else { + sopv = &ex.lsReplyHeader().srcPosVector(); + } + } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_geoAnycastHdr)) { // Receive a GeoAnycast + sopv = &ex.geoAnycastHeader().srcPosVector(); + } else if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_geoUnicastHdr)) { + sopv = &ex.geoUnicastHeader().srcPosVector(); + } // else, nothing to do + loggers::get_instance().log("geonetworking_layer::receive_data: sopv is bound: %d", sopv->is_bound()); + if (sopv->is_bound()) { + const LibItsGeoNetworking__TypesAndValues::LongPosVector &lpv = *sopv; + _location_table.add_entry(lpv); + } + } + + // By default incoming beacons are filtered by the test adapter + if (htst.ischosen(LibItsGeoNetworking__TypesAndValues::HeaderTST::ALT_beaconHdr)) { + loggers::get_instance().log_msg("geonetworking_layer::receive_data: Pass beaconing filtering: ", sopv->gnAddr().mid()); + if (_pass_beacon_table.empty()) { // Discard beacon + loggers::get_instance().log("geonetworking_layer::receive_data: Pass beaconing table empty, discard it"); + return; + } else { // Check beacon filter for StartPassBeaconing/Stop + if (!_pass_beacon_table.has_entry(sopv->gnAddr().mid())) { // Discard beacon + loggers::get_instance().log_msg("geonetworking_layer::receive_data: Not in pass beaconing table, discard it", *sopv); + return; + } // else, continue + } + } // else, continue + } else { + // Inavlid GeoNetworking payload, discard it + loggers::get_instance().warning("geonetworking_layer::receive_data: Failed to decode payload, discard it"); + return; + } + + // Add lower layers parameters + // 1. Destination MAC address + params::const_iterator it = params.find(params::mac_dst); + if (it != params.cend()) { + loggers::get_instance().log("geonetworking_layer::receive_data: dst=%s", it->second.c_str()); + ind.macDestinationAddress() = str2oct(CHARSTRING(it->second.c_str())); + } else { + ind.macDestinationAddress() = str2oct(CHARSTRING(_params["mac_bc"].c_str())); + } + // 2. ssp + it = params.find(params::ssp); + if (it != params.cend()) { + loggers::get_instance().log("geonetworking_layer::receive_data: ssp=%s", it->second.c_str()); + ind.ssp() = oct2bit(str2oct(CHARSTRING(it->second.c_str()))); + } else { + ind.ssp().set_to_omit(); + } + // 3. its_aid + it = params.find(params::its_aid); + if (it != params.cend()) { + loggers::get_instance().log("geonetworking_layer::receive_data: its_aid=%s", it->second.c_str()); + ind.its__aid() = std::stoi(it->second.c_str()); + } else { + ind.its__aid().set_to_omit(); + } + + // Pass the GeoNetworking raw payload to the upper layers if any + it = params.find(params::gn_payload); + if (it != params.cend()) { + loggers::get_instance().log("geonetworking_layer::receive_data: gn_payload=%s", it->second.c_str()); + OCTETSTRING os(str2oct(CHARSTRING(it->second.c_str()))); + receive_to_all_layers(os, params); + } else { + loggers::get_instance().warning("geonetworking_layer::receive_data: No payload to pass to upper layers"); + } + + // Pass it to the ports + to_all_upper_ports(ind, params); +} + +OCTETSTRING geonetworking_layer::trigger_ac_event(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_to_hexa(">>> geonetworking_layer::trigger_ac_event: ", data); + + return int2oct(0, 2); +} // End of trigger_ac_event method + +void geonetworking_layer::start_beaconing() { + loggers::get_instance().log(">>> geonetworking_layer::start_beaconing"); + // loggers::get_instance().log_msg("geonetworking_layer::start_beaconing: _beacon=", *_beacon); + + // Establish handler for timer signal + loggers::get_instance().log("geonetworking_layer::start_beaconing: Establishing handler for signal %d\n", _signal_id); + _sa.sa_flags = SA_SIGINFO; + _sa.sa_sigaction = timer_irq_sigalrm_handler; + sigemptyset(&_sa.sa_mask); + if (sigaction(_signal_id, &_sa, nullptr) == -1) { + loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigaction failure: %d", errno); + } + // Block timer signal temporarily + loggers::get_instance().log("geonetworking_layer::start_beaconing: Blocking signal %d\n", _signal_id); + sigemptyset(&_mask); + sigaddset(&_mask, _signal_id); + if (sigprocmask(SIG_SETMASK, &_mask, nullptr) == -1) { + loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigprocmask failure: %d", errno); + } + // Create the timer + _sev.sigev_notify = SIGEV_SIGNAL; + _sev.sigev_signo = _signal_id; // Use signal alarm + _sev.sigev_value.sival_ptr = this; // The geonetworking_layer object address + if (timer_create(CLOCK_REALTIME, &_sev, &_timerid) == -1) { + loggers::get_instance().error("geonetworking_layer::start_beaconing: Timer failure: %d", errno); + } + loggers::get_instance().log("geonetworking_layer::start_beaconing: timer ID is 0x%x\n", (long)_timerid); + // Start the timer + unsigned int expiry = 1000; // Default expiry time 1000ms + params::const_iterator i = _params.find("expiry"); + if (i != _params.cend()) { + expiry = static_cast(std::strtoul(i->second.c_str(), nullptr, 10)); + } + _freq_nanosecs = expiry * 1000000; + _its.it_value.tv_sec = _freq_nanosecs / 1000000000; + _its.it_value.tv_nsec = _freq_nanosecs % 1000000000; + _its.it_interval.tv_sec = _its.it_value.tv_sec; + _its.it_interval.tv_nsec = _its.it_value.tv_nsec; + if (timer_settime(_timerid, 0, &_its, nullptr) == -1) { + loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigprocmask failure: %d", errno); + } + // Unlock the timer signal, so that timer notification can be delivered + loggers::get_instance().log("geonetworking_layer::start_beaconing: Unblocking signal %d\n", _signal_id); + if (sigprocmask(SIG_UNBLOCK, &_mask, nullptr) == -1) { + loggers::get_instance().error("geonetworking_layer::start_beaconing: Sigprocmask failure: %d", errno); + } +} // End of start_beaconing method + +void geonetworking_layer::start_beaconing(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &p_beacon) { + loggers::get_instance().log_msg(">>> geonetworking_layer::start_beaconing", p_beacon); + + // Initialize the beacon + if (_beacon != nullptr) { + delete _beacon; + } + _beacon = new LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu(p_beacon); + + start_beaconing(); // TODO Refined adding a boolean return code +} // End of start_beaconing method + +void geonetworking_layer::stop_beaconing() { + loggers::get_instance().log(">>> geonetworking_layer::stop_beaconing"); + + // Block timer signal temporarily + loggers::get_instance().log("geonetworking_layer::stop_beaconing: Blocking signal %d\n", _signal_id); + sigemptyset(&_mask); + sigaddset(&_mask, _signal_id); + if (sigprocmask(SIG_SETMASK, &_mask, nullptr) == -1) { + loggers::get_instance().error("geonetworking_layer::stop_beaconing: Sigprocmask failure: %d", errno); + } + timer_delete(_timerid); + _timerid = 0; +} // End of stop_beaconing method + +void geonetworking_layer::send_beacon() { + loggers::get_instance().log(">>> geonetworking_layer::send_beacon"); + + ExtendedHeader *eh = static_cast(_beacon->gnPacket().packet().extendedHeader().get_opt_value()); + if (eh == nullptr) { + loggers::get_instance().error("geonetworking_layer::send_beacon: Wrong cast"); + } + // Update timestamp + eh->beaconHeader().srcPosVector().timestamp__().set_long_long_val((unsigned int)base_time::get_instance().get_its_current_time_mod_ms()); + // loggers::get_instance().log_msg("geonetworking_layer::send_beacon: ", *_beacon); + // Encode message using TITAN because of payload in omited + TTCN_Buffer encoding_buffer; + _beacon->encode(*(_beacon->get_descriptor()), encoding_buffer, TTCN_EncDec::CT_RAW); + OCTETSTRING data(encoding_buffer.get_len(), encoding_buffer.get_data()); + params params(_params); + if (_secured_mode) { // Apply Security + if (build_secured_pdu(data, _params) != 0) { + return; + } + } + // Send it + // TODO To be removed + while (_sendData.try_lock() == FALSE) { + // not ready yet + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } // End of 'while' statement + send_to_all_layers(data, params); + _sendData.unlock(); + + // loggers::get_instance().log("<<< geonetworking_layer::send_beacon"); +} // End of send_beacon method + +void geonetworking_layer::start_pass_beaconing(const LibItsGeoNetworking__TypesAndValues::BeaconHeader &p_beacon) { + loggers::get_instance().log_msg(">>> geonetworking_layer::start_pass_beaconing", p_beacon); + + const LibItsGeoNetworking__TypesAndValues::LongPosVector &lpv = p_beacon.srcPosVector(); + if (!_pass_beacon_table.has_entry(lpv.gnAddr().mid())) { + _pass_beacon_table.add_entry(lpv); + } // TODO Refined adding a boolean return code +} // End of start_pass_beaconing method + +void geonetworking_layer::stop_pass_beaconing() { + loggers::get_instance().log(">>> geonetworking_layer::stop_pass_beaconing"); + + _pass_beacon_table.reset(); +} // End of stop_pass_beaconing method + +int geonetworking_layer::enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security) { + loggers::get_instance().log(">>> geonetworking_layer::enable_secured_mode: '%s' - %x", p_certificate_id.c_str(), p_enforce_security); + + loggers::get_instance().log("geonetworking_layer::enable_secured_mode: _secured_mode = %x", _secured_mode); + if (!_secured_mode) { + loggers::get_instance().log("geonetworking_layer::enable_secured_mode: Setup secured mode"); + _secured_mode = true; + setup_secured_mode(); + } + _enable_security_checks = p_enforce_security; + params::const_iterator it = _params.find(params::certificate); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("certificate"), p_certificate_id)); + } else { + _params[params::certificate] = p_certificate_id; + } + loggers::get_instance().log("geonetworking_layer::enable_secured_mode: Certificate to be used: '%s'", _params[params::certificate].c_str()); + + return 0; +} + +int geonetworking_layer::disable_secured_mode() { + loggers::get_instance().log(">>> geonetworking_layer::disable_secured_mode"); + _secured_mode = false; + _enable_security_checks = false; + return 0; +} + +const LongPosVector *geonetworking_layer::get_lpv(const GN__Address &p_gn_address) { + loggers::get_instance().log_msg(">>> geonetworking_layer::get_lpv", p_gn_address); + + const LongPosVector *lpv = nullptr; + if (_location_table.has_entry(p_gn_address.mid())) { + lpv = _location_table.get_entry(p_gn_address.mid()); + } + return lpv; +} // End of get_lpv + +const LibItsGeoNetworking__TypesAndValues::BasicHeader geonetworking_layer::fill_basic_header() const { + return LibItsGeoNetworking__TypesAndValues::BasicHeader(1, // GeoNetworking version + BasicNextHeader(BasicNextHeader::e__commonHeader), 0, Lifetime(4, LtBase(LtBase::e__50ms)), 1); +} + +void geonetworking_layer::fill_beacon(const OCTETSTRING &p_ll_address, const INTEGER p_station_type, const INTEGER p_country, const INTEGER type_of_address) { + _beacon = new GeoNetworkingPdu(); + HeaderTST h; + h.beaconHdr() = BeaconHeaderType(HeaderType(HeaderType::e__beacon), 0); + ExtendedHeader eh; + eh.beaconHeader() = + BeaconHeader(LongPosVector(GN__Address(TypeOfAddress((TypeOfAddress)type_of_address), StationType((StationType)p_station_type), p_country, p_ll_address), 0, + _latitude, _longitude, int2bit(0, 1), 0, 0)); + _beacon->basicHeader() = fill_basic_header(); + _beacon->gnPacket().packet() = + GnNonSecuredPacket(CommonHeader(NextHeader(NextHeader::e__any), 0, h, + TrafficClass(SCF(SCF::e__scfEnabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), int2bit(0, 8), 0, 1, 0), + OPTIONAL(eh), OPTIONAL()); + _beacon->gnPacket().packet().payload().set_to_omit(); + _beacon->gnPacket().securedMsg().set_to_omit(); + // loggers::get_instance().log_msg("geonetworking_layer::fill_beacon: beacon value: ", *_beacon); +} // End of fill_beacon method + +void geonetworking_layer::fill_gbc_packet(const OCTETSTRING &p_ll_address, const INTEGER &p_geoAreaPosLatitude, const INTEGER &p_geoAreaPosLongitude, + const INTEGER &p_distanceA, const INTEGER &p_distanceB, const INTEGER &p_angle) { + _gbc_packet = new GeoNetworkingPdu(); + HeaderTST h; + h.geoBroadcastHdr() = + GeoBroadcastHeaderType(HeaderType(HeaderType::e__geoBroadcast), HeaderSubTypeGeoBroadcast(HeaderSubTypeGeoBroadcast::e__geoBroadcastElip)); + ExtendedHeader eh; + eh.geoBroadcastHeader() = GeoAnycastHeader( // GeoBradcastHeader is identical as GeoAnycastHeader + 0, 0, + LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude, _longitude, int2bit(1, 1), // PAI + 0, 0), + p_geoAreaPosLatitude, p_geoAreaPosLongitude, p_distanceA, p_distanceB, p_angle, 0); + _gbc_packet->basicHeader() = fill_basic_header(); + _gbc_packet->gnPacket().packet() = GnNonSecuredPacket( + CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), + int2bit(128, 8), // Mobile stationnary flag set + 0, 5, 0), + OPTIONAL(eh), OPTIONAL()); + _gbc_packet->gnPacket().packet().payload().set_to_omit(); + _gbc_packet->gnPacket().securedMsg().set_to_omit(); + // loggers::get_instance().log_msg("geonetworking_layer::fill_gbc_packet: packet value: ", *_gbc_packet); +} // End of fill_gbc_packet method + +void geonetworking_layer::fill_shb_packet(const OCTETSTRING &p_ll_address) { + _shb_packet = new GeoNetworkingPdu(); + HeaderTST h; + h.tsbHdr() = TsbHeaderType(HeaderType(HeaderType::e__topologicallyScopedBroadcast), HeaderSubTypeTSB(HeaderSubTypeTSB::e__singleHop)); + ExtendedHeader eh; + eh.shbHeader() = SHBHeader(LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude, _longitude, int2bit(1, 1), // PAI + 0, 0), + 0); + _shb_packet->basicHeader() = fill_basic_header(); + _shb_packet->gnPacket().packet() = GnNonSecuredPacket( + CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), + int2bit(128, 8), // Mobile stationnary flag set + 0, 1, 0), + OPTIONAL(eh), OPTIONAL()); + _shb_packet->gnPacket().packet().payload().set_to_omit(); + _shb_packet->gnPacket().securedMsg().set_to_omit(); + // loggers::get_instance().log_msg("geonetworking_layer::fill_shb_packet: packet value: ", *_shb_packet); +} // End of fill_shb_packet method + +void geonetworking_layer::fill_tsb_packet(const OCTETSTRING &p_ll_address, const int p_hop_number, const int p_max_hop_limit) { + _tsb_packet = new GeoNetworkingPdu(); + HeaderTST h; + h.tsbHdr() = TsbHeaderType(HeaderType(HeaderType::e__topologicallyScopedBroadcast), HeaderSubTypeTSB(HeaderSubTypeTSB::e__multiHop)); + ExtendedHeader eh; + eh.tsbHeader() = TSBHeader(0, 0, + LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude, _longitude, int2bit(1, 1), // PAI + 0, 0)); + _tsb_packet->basicHeader() = fill_basic_header(); + _tsb_packet->gnPacket().packet() = GnNonSecuredPacket( + CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), + int2bit(128, 8), // Mobile stationnary flag set + 0, p_max_hop_limit, 0), + OPTIONAL(eh), OPTIONAL()); + _tsb_packet->gnPacket().packet().payload().set_to_omit(); + _tsb_packet->gnPacket().securedMsg().set_to_omit(); + // loggers::get_instance().log_msg("geonetworking_layer::fill_tsb_packet: packet value: ", *_tsb_packet); +} // End of fill_tsb_packet method + +void geonetworking_layer::fill_uni_packet(const OCTETSTRING &p_ll_address, const int p_hop_number, const int p_max_hop_limit) { + _uni_packet = new GeoNetworkingPdu(); + HeaderTST h; + h.geoUnicastHdr() = GeoUnicastHeaderType(HeaderType(HeaderType::e__geoUnicast), 0); + ExtendedHeader eh; + eh.geoUnicastHeader() = GeoUnicastHeader(0, 0, + LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude, _longitude, int2bit(1, 1), // PAI + 0, 0), + ShortPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude + 100, _longitude + 100)); + _uni_packet->basicHeader() = fill_basic_header(); + _uni_packet->gnPacket().packet() = GnNonSecuredPacket( + CommonHeader(NextHeader(NextHeader::e__btpA), 0, h, TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), + int2bit(128, 8), // Mobile stationnary flag set + 0, p_max_hop_limit, 0), + OPTIONAL(eh), OPTIONAL()); + _uni_packet->gnPacket().packet().payload().set_to_omit(); + _uni_packet->gnPacket().securedMsg().set_to_omit(); + // loggers::get_instance().log_msg("geonetworking_layer::fill_uni_packet: packet value: ", *_uni_packet); +} // End of fill_uni_packet method + +void geonetworking_layer::fill_ls_reply(const OCTETSTRING &p_ll_address) { + _ls_reply = new GeoNetworkingPdu(); + HeaderTST h; + h.lsHdr() = LsHeaderType(HeaderType(HeaderType::e__locationService), HeaderSubTypeLs(HeaderSubTypeLs::e__lsReply)); + ExtendedHeader eh; + eh.lsReplyHeader() = LSReplyHeader(0, 0, + LongPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude, _longitude, int2bit(1, 1), // PAI + 0, 0), + ShortPosVector(GN__Address(TypeOfAddress(TypeOfAddress::e__manual), // TODO Use params + StationType(StationType::e__passengerCar), // TODO Use params + 33, p_ll_address), + 0, _latitude, _longitude)); + _ls_reply->basicHeader() = fill_basic_header(); + _ls_reply->gnPacket().packet() = GnNonSecuredPacket(CommonHeader(NextHeader(NextHeader::e__any), 0, h, + TrafficClass(SCF(SCF::e__scfDisabled), ChannelOffload(ChannelOffload::e__choffDisabled), 0), + int2bit(128, 8), // Mobile stationnary flag set + 0, 5, 0), + OPTIONAL(eh), OPTIONAL()); + _ls_reply->gnPacket().packet().payload().set_to_omit(); + _ls_reply->gnPacket().securedMsg().set_to_omit(); + // loggers::get_instance().log_msg("geonetworking_layer::fill_ls_reply: packet value: ", *_ls_reply); +} // End of fill_ls_reply method + +void geonetworking_layer::timer_irq_sigalrm_handler(int p_signal, siginfo_t *p_signal_info, void *p_uc) { + // loggers::get_instance().log(">>> geonetworking_layer::timer_irq_sigalrm_handler: Caught signal %d", p_signal); + + static_cast(p_signal_info->si_value.sival_ptr)->send_beacon(); +} // End of method timer_irq_sigalrm_handler + +int geonetworking_layer::build_geonetworking_pdu(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> geonetworking_layer::build_geonetworking_pdu"); + // params.log(); + + std::string next_header; + params::const_iterator it = params.find(params::next_header); + if (it != params.cend()) { + next_header = it->second.c_str(); + } + std::string header_type; + it = params.find(params::header_type); + if (it != params.cend()) { + header_type = it->second.c_str(); + } + std::string header_sub_type; + it = params.find(params::header_sub_type); + if (it != params.cend()) { + header_sub_type = it->second.c_str(); + } + loggers::get_instance().log("geonetworking_layer::build_geonetworking_pdu: %s, %s, %s", next_header.c_str(), header_type.c_str(), header_sub_type.c_str()); + + if (header_type.compare("tsb") == 0) { + if (header_sub_type.compare("sh") == 0) { // Use SHB + ExtendedHeader *eh = static_cast(_shb_packet->gnPacket().packet().extendedHeader().get_opt_value()); + if (eh == nullptr) { + loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); + return -1; + } + // Update NextHeader + it = params.find(params::next_header); + if (next_header.compare("btpB") == 0) { + _shb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; + } else { // Default btp is btpA + _shb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; + } + // Update payload + _shb_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); + _shb_packet->gnPacket().packet().payload() = OPTIONAL(data); + // Update timestamp + eh->shbHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); + + loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: shb: ", *_shb_packet); + // Encode GeoNetworking PDU + OCTETSTRING os; + _codec.encode(*_shb_packet, os); + data = os; + } else { // Use TSB + ExtendedHeader *eh = static_cast(_tsb_packet->gnPacket().packet().extendedHeader().get_opt_value()); + if (eh == nullptr) { + loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); + return -1; + } + // Update sequence number + eh->tsbHeader().seqNumber() = _sequence_number++; + // Update NextHeader + it = params.find(params::next_header); + if (next_header.compare("btpB") == 0) { + _tsb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; + } else { // Default btp is btpA + _tsb_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; + } + // Update payload + _tsb_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); + _tsb_packet->gnPacket().packet().payload() = OPTIONAL(data); + // Update timestamp + eh->tsbHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); + + loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: tsb: ", *_tsb_packet); + // Encode GeoNetworking PDU + OCTETSTRING os; + _codec.encode(*_tsb_packet, os); + data = os; + } + } else if (header_type.compare("uni") == 0) { + ExtendedHeader *eh = static_cast(_uni_packet->gnPacket().packet().extendedHeader().get_opt_value()); + if (eh == nullptr) { + loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); + return -1; + } + // Update NextHeader + it = params.find(params::next_header); + if (next_header.compare("btpB") == 0) { + _uni_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; + } else { // Default btp is btpA + _uni_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; + } + // Update sequence number + eh->geoUnicastHeader().seqNumber() = _sequence_number++; + // Update payload + _uni_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); + _uni_packet->gnPacket().packet().payload() = OPTIONAL(data); + // Update timestamp + eh->geoUnicastHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); + + loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: uni: ", *_uni_packet); + + // Encode GeoNetworking PDU + OCTETSTRING os; + _codec.encode(*_uni_packet, os); + data = os; + } else { // TODO To be continued + // Default: Use GBC + ExtendedHeader *eh = static_cast(_gbc_packet->gnPacket().packet().extendedHeader().get_opt_value()); + if (eh == nullptr) { + loggers::get_instance().error("geonetworking_layer::build_geonetworking_pdu: Wrong cast"); + return -1; + } + // Update NextHeader + it = params.find(params::next_header); + if (next_header.compare("btpB") == 0) { + _gbc_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpB; + } else { // Default btp is btpA + _gbc_packet->gnPacket().packet().commonHeader().nextHeader() = NextHeader::e__btpA; + } + // Update sequence number + eh->geoBroadcastHeader().seqNumber() = _sequence_number++; + // Update payload + _gbc_packet->gnPacket().packet().commonHeader().plLength() = data.lengthof(); + _gbc_packet->gnPacket().packet().payload() = OPTIONAL(data); + // Update timestamp + eh->geoBroadcastHeader().srcPosVector().timestamp__().set_long_long_val(static_cast(base_time::get_instance().get_its_current_time_mod_ms())); + + loggers::get_instance().log_msg("geonetworking_layer::build_geonetworking_pdu: gbc: ", *_gbc_packet); + + // Encode GeoNetworking PDU + OCTETSTRING os; + _codec.encode(*_gbc_packet, os); + data = os; + } + + return 0; +} + +int geonetworking_layer::build_secured_pdu(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> geonetworking_layer::build_secured_pdu: ", data); + // params.log(); + + LibItsGeoNetworking__TypesAndValues::BasicHeader basic_header; + decode_basic_header(data, basic_header); + if (basic_header.nextHeader() == BasicNextHeader::e__securedPacket) { // Already secured (ATS Security test suite/f_sendSecuredGn/Cam/Denm TTCN-3 functions + // Leave data unchanged + loggers::get_instance().log_msg("<<< geonetworking_layer::build_secured_pdu: Leave data unchanged: ", data); + return 0; + } + // Update security mode + unsigned int basic_header_len = 4; // FIXME How to retrive the BasicHeader length basic_header.get_descriptor()->raw->fieldlength / 8; + loggers::get_instance().log("geonetworking_layer::build_secured_pdu: basic_header_len = %d", basic_header_len); + basic_header.nextHeader() = BasicNextHeader::e__securedPacket; + OCTETSTRING unsecured_gn_payload = OCTETSTRING(data.lengthof() - basic_header_len, static_cast(data) + basic_header_len); + OCTETSTRING secured_gn_payload; + if (security_services::get_instance().secure_gn_payload(unsecured_gn_payload, secured_gn_payload, params) != 0) { + loggers::get_instance().warning("geonetworking_layer::build_secured_pdu: failed to build secured pdu"); + return -1; + } + + // Encode the basic header + // loggers::get_instance().log_msg("geonetworking_layer::build_secured_pdu: New basic_header = ", basic_header); + RAW_enc_tr_pos rp; + rp.level = 0; + rp.pos = NULL; + RAW_enc_tree enc_tree(FALSE, NULL, &rp, 1, basic_header.get_descriptor()->raw); + basic_header.RAW_encode(*basic_header.get_descriptor(), enc_tree); + TTCN_Buffer encoding_buffer; + enc_tree.put_to_buf(encoding_buffer); + // Copy result + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()) + secured_gn_payload; + loggers::get_instance().log_msg("geonetworking_layer::build_secured_pdu: Secured pdu = ", data); + + return 0; +} + +int geonetworking_layer::decode_basic_header(const OCTETSTRING &p_data, LibItsGeoNetworking__TypesAndValues::BasicHeader &p_basic_header) { + // loggers::get_instance().log_msg(">>> geonetworking_layer::decode_basic_header: ", p_data); + + // Update security mode + OCTETSTRING bh = + OCTETSTRING(4, static_cast(p_data)); // Extract the basic header as specified in ETSI EN 302 636-4-1 V1.3.1 (2017-08) Clause 9.6 + // loggers::get_instance().log_msg("geonetworking_layer::decode_basic_header: bh: ", bh); + TTCN_Buffer decoding_buffer(bh); + p_basic_header.RAW_decode(*p_basic_header.get_descriptor(), decoding_buffer, decoding_buffer.get_len() * 8, raw_order_t::ORDER_MSB); + // loggers::get_instance().log_msg("geonetworking_layer::decode_basic_header: ", p_basic_header); + + return 0; +} + +int geonetworking_layer::setup_secured_mode() { + loggers::get_instance().log(">>> geonetworking_layer::setup_secured_mode"); + + loggers::get_instance().log("geonetworking_layer::setup_secured_mode: GN Layer address = %p", this); + + params::const_iterator it = _params.find(params::certificate); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("certificate"), "CERT_TS_A_AT")); + } + it = _params.find(params::sec_db_path); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("sec_db_path"), "")); + } + it = _params.find(params::hash); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("hash"), "SHA-256")); + } + it = _params.find(params::signature); // TODO Should be removed + if (it == _params.cend()) { + _params.insert(std::pair(std::string("signature"), "NISTP-256")); + } + // Set up security services even if secured_mode is set to 0. Later, we can receive an AcEnableSecurity request, the sertificate caching will be ready to go + security_services::get_instance().setup(_params); + security_services::get_instance().set_position(_latitude, _longitude); + + return 0; +} + +geonetworking_layer_factory geonetworking_layer_factory::_f; diff --git a/ccsrc/Protocols/GeoNetworking/geonetworking_layer.hh b/ccsrc/Protocols/GeoNetworking/geonetworking_layer.hh index 39bd4a058c7e53195d3e88b86b0c70219dd5d28f..2b4ff6c0fe6b4f9a77e7543e24d8834761c91809 100644 --- a/ccsrc/Protocols/GeoNetworking/geonetworking_layer.hh +++ b/ccsrc/Protocols/GeoNetworking/geonetworking_layer.hh @@ -1,198 +1,198 @@ -/*! - * \file geonetworking_layer.hh - * \brief Header file for ITS GeoNetworking protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include - -#include - -#include "geonetworking_codec.hh" -#include "location_table.hh" -#include "t_layer.hh" - -class INTEGER; //! Forward declaration of TITAN class -class OCTETSTRING; //! Forward declaration of TITAN class - -namespace LibItsGeoNetworking__TestSystem { - class GeoNetworkingPort; //! Forward declaration of TITAN class - class GeoNetworkingReq; //! Forward declaration of TITAN class - class GeoNetworkingInd; //! Forward declaration of TITAN class -} // namespace LibItsGeoNetworking__TestSystem - -namespace LibItsGeoNetworking__TypesAndValues { - class BasicHeader; //! Forward declaration of TITAN class - class GeoNetworkingPdu; //! Forward declaration of TITAN class - class BeaconHeader; //! Forward declaration of TITAN class - class LongPosVector; //! Forward declaration of TITAN class - class GN__Address; //! Forward declaration of TITAN class -} // namespace LibItsGeoNetworking__TypesAndValues - -// TODO Change pointers into smart pointers -/*! - * \class geonetworking_layer - * \brief This class provides description of ITS GeoNetworking protocol layer - */ -class geonetworking_layer : public t_layer { - params _params; /*!< Layer parameters */ - geonetworking_codec _codec; /*!< GeoNetworking codec object reference. \see geonetworking_codec */ - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu *_beacon; /*!< Data structure used for beaconing */ - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu - *_gbc_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a Geobroadcast */ - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu - *_shb_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a SHB */ - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu - *_tsb_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a TSB */ - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu - *_uni_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a Unicast */ - LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu *_ls_reply; /*!< Data structure used to reply to an incoming LS_REQUEST */ - location_table _location_table; /*!< Location table, used when device_mode is set */ - location_table _pass_beacon_table; /*!< Beaconing filter table */ - bool _device_mode; - bool _secured_mode; - bool _encrypted_mode; - bool _enable_security_checks; - std::mutex _sendData; // FIXME To be removed, useless - timer_t _timerid; - struct sigevent _sev; - struct itimerspec _its; - long long _freq_nanosecs; - sigset_t _mask; - struct sigaction _sa; - unsigned int _sequence_number; - int _latitude; - int _longitude; - - /*! - * \brief Create and initialize a BasicHeader object - * \return A BasicHeader object - */ - const LibItsGeoNetworking__TypesAndValues::BasicHeader fill_basic_header() const; - /*! - * \brief Initialize a beacon object for a stand alone beaconing - * This object could be replaced in case of start_beaconing call from the Adapter Control Port - * \param[in] p_latitude - * \param[in] p_longitude - * \param[in] p_address - */ - void fill_beacon(const OCTETSTRING &p_ll_address, const INTEGER p_station_type = 5, const INTEGER p_country = 0, const INTEGER type_of_address = 1); - /*! - * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages - * This object shall be updated before to be sent - * \param[in] p_latitude - * \param[in] p_longitude - * \param[in] p_address - */ - void fill_gbc_packet(const OCTETSTRING &p_ll_address, const INTEGER &p_geoAreaPosLatitude, const INTEGER &p_geoAreaPosLongitude, const INTEGER &p_distanceA, - const INTEGER &p_distanceB, const INTEGER &p_angle); - /*! - * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages - * This object shall be updated before to be sent - * \param[in] p_latitude - * \param[in] p_longitude - * \param[in] p_address - */ - void fill_shb_packet(const OCTETSTRING &p_ll_address); - /*! - * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages - * This object shall be updated before to be sent - * \param[in] p_latitude - * \param[in] p_longitude - * \param[in] p_address - * \param[in] p_hop_number - * \param[in] p_max_hop_number - */ - void fill_tsb_packet(const OCTETSTRING &p_ll_address, const int p_hop_number = 3, const int p_max_hop_limit = 5); - /*! - * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages - * This object shall be updated before to be sent - * \param[in] p_latitude - * \param[in] p_longitude - * \param[in] p_address - * \param[in] p_hop_number - * \param[in] p_max_hop_number - */ - void fill_uni_packet(const OCTETSTRING &p_ll_address, const int p_hop_number = 3, const int p_max_hop_limit = 5); - /*! - * \brief Initialize an LS_REPLY GeoNetworking packet to reply to an LS_REQUEST - * This object shall be updated before to be sent - * \param[in] p_latitude - * \param[in] p_longitude - * \param[in] p_address - */ - void fill_ls_reply(const OCTETSTRING &p_ll_address); - - static void timer_irq_sigalrm_handler(int p_signal, siginfo_t *p_signal_info, void *p_uc); - - const int _signal_id = SIGTERM; - -public: - explicit geonetworking_layer() - : t_layer(), _params(), _codec(), _beacon(NULL), _gbc_packet(NULL), _shb_packet(nullptr), - _ls_reply(nullptr), _location_table(), _pass_beacon_table(), _device_mode{false}, _sendData(), _timerid{0}, _sev{0}, _its{0}, - _freq_nanosecs(0), _mask{0}, _sa{0}, _sequence_number{0} {}; - geonetworking_layer(const std::string &p_type, const std::string &p_param); - virtual ~geonetworking_layer(); - - /*! - * \fn void sendMsg(const LibItsGeoNetworking__TestSystem::GeoNetworkingReq& p_gn_req, params& p_param); - * \brief Send GeoNetworking message to the lower layers - * \param[in] p_gn_req The GeoNetworking message to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - void sendMsg(const LibItsGeoNetworking__TestSystem::GeoNetworkingReq &p_gn_req, params &p_param); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual OCTETSTRING trigger_ac_event(OCTETSTRING &data, params ¶ms); - - const LibItsGeoNetworking__TypesAndValues::LongPosVector *get_lpv(const LibItsGeoNetworking__TypesAndValues::GN__Address &p_gn_address); - void start_beaconing(); - void start_beaconing(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &p_beacon); - void stop_beaconing(); - void start_pass_beaconing(const LibItsGeoNetworking__TypesAndValues::BeaconHeader &p_beacon); - void stop_pass_beaconing(); - - int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security = false); - int disable_secured_mode(); - -private: - void init(const std::string &p_type, const std::string &p_param); - void send_beacon(); - int build_geonetworking_pdu(OCTETSTRING &data, params ¶ms); - int build_secured_pdu(OCTETSTRING &data, params ¶ms); - int decode_basic_header(const OCTETSTRING &p_data, LibItsGeoNetworking__TypesAndValues::BasicHeader &p_basic_header); - int setup_secured_mode(); - -}; // End of class geonetworking_layer +/*! + * \file geonetworking_layer.hh + * \brief Header file for ITS GeoNetworking protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include + +#include + +#include "geonetworking_codec.hh" +#include "location_table.hh" +#include "t_layer.hh" + +class INTEGER; //! Forward declaration of TITAN class +class OCTETSTRING; //! Forward declaration of TITAN class + +namespace LibItsGeoNetworking__TestSystem { + class GeoNetworkingPort; //! Forward declaration of TITAN class + class GeoNetworkingReq; //! Forward declaration of TITAN class + class GeoNetworkingInd; //! Forward declaration of TITAN class +} // namespace LibItsGeoNetworking__TestSystem + +namespace LibItsGeoNetworking__TypesAndValues { + class BasicHeader; //! Forward declaration of TITAN class + class GeoNetworkingPdu; //! Forward declaration of TITAN class + class BeaconHeader; //! Forward declaration of TITAN class + class LongPosVector; //! Forward declaration of TITAN class + class GN__Address; //! Forward declaration of TITAN class +} // namespace LibItsGeoNetworking__TypesAndValues + +// TODO Change pointers into smart pointers +/*! + * \class geonetworking_layer + * \brief This class provides description of ITS GeoNetworking protocol layer + */ +class geonetworking_layer : public t_layer { + params _params; /*!< Layer parameters */ + geonetworking_codec _codec; /*!< GeoNetworking codec object reference. \see geonetworking_codec */ + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu *_beacon; /*!< Data structure used for beaconing */ + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu + *_gbc_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a Geobroadcast */ + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu + *_shb_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a SHB */ + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu + *_tsb_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a TSB */ + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu + *_uni_packet; /*!< Data structure used to encapsulate upper layer PDU into a GeoNetworking packet as a Unicast */ + LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu *_ls_reply; /*!< Data structure used to reply to an incoming LS_REQUEST */ + location_table _location_table; /*!< Location table, used when device_mode is set */ + location_table _pass_beacon_table; /*!< Beaconing filter table */ + bool _device_mode; + bool _secured_mode; + bool _encrypted_mode; + bool _enable_security_checks; + std::mutex _sendData; // FIXME To be removed, useless + timer_t _timerid; + struct sigevent _sev; + struct itimerspec _its; + long long _freq_nanosecs; + sigset_t _mask; + struct sigaction _sa; + unsigned int _sequence_number; + int _latitude; + int _longitude; + + /*! + * \brief Create and initialize a BasicHeader object + * \return A BasicHeader object + */ + const LibItsGeoNetworking__TypesAndValues::BasicHeader fill_basic_header() const; + /*! + * \brief Initialize a beacon object for a stand alone beaconing + * This object could be replaced in case of start_beaconing call from the Adapter Control Port + * \param[in] p_latitude + * \param[in] p_longitude + * \param[in] p_address + */ + void fill_beacon(const OCTETSTRING &p_ll_address, const INTEGER p_station_type = 5, const INTEGER p_country = 0, const INTEGER type_of_address = 1); + /*! + * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages + * This object shall be updated before to be sent + * \param[in] p_latitude + * \param[in] p_longitude + * \param[in] p_address + */ + void fill_gbc_packet(const OCTETSTRING &p_ll_address, const INTEGER &p_geoAreaPosLatitude, const INTEGER &p_geoAreaPosLongitude, const INTEGER &p_distanceA, + const INTEGER &p_distanceB, const INTEGER &p_angle); + /*! + * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages + * This object shall be updated before to be sent + * \param[in] p_latitude + * \param[in] p_longitude + * \param[in] p_address + */ + void fill_shb_packet(const OCTETSTRING &p_ll_address); + /*! + * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages + * This object shall be updated before to be sent + * \param[in] p_latitude + * \param[in] p_longitude + * \param[in] p_address + * \param[in] p_hop_number + * \param[in] p_max_hop_number + */ + void fill_tsb_packet(const OCTETSTRING &p_ll_address, const int p_hop_number = 3, const int p_max_hop_limit = 5); + /*! + * \brief Initialize a GeoNetworking packet to send GeoNetworking Facility messages + * This object shall be updated before to be sent + * \param[in] p_latitude + * \param[in] p_longitude + * \param[in] p_address + * \param[in] p_hop_number + * \param[in] p_max_hop_number + */ + void fill_uni_packet(const OCTETSTRING &p_ll_address, const int p_hop_number = 3, const int p_max_hop_limit = 5); + /*! + * \brief Initialize an LS_REPLY GeoNetworking packet to reply to an LS_REQUEST + * This object shall be updated before to be sent + * \param[in] p_latitude + * \param[in] p_longitude + * \param[in] p_address + */ + void fill_ls_reply(const OCTETSTRING &p_ll_address); + + static void timer_irq_sigalrm_handler(int p_signal, siginfo_t *p_signal_info, void *p_uc); + + const int _signal_id = SIGTERM; + +public: + explicit geonetworking_layer() + : t_layer(), _params(), _codec(), _beacon(NULL), _gbc_packet(NULL), _shb_packet(nullptr), + _ls_reply(nullptr), _location_table(), _pass_beacon_table(), _device_mode{false}, _sendData(), _timerid{0}, _sev{0}, _its{0}, + _freq_nanosecs(0), _mask{0}, _sa{0}, _sequence_number{0} {}; + geonetworking_layer(const std::string &p_type, const std::string &p_param); + virtual ~geonetworking_layer(); + + /*! + * \fn void sendMsg(const LibItsGeoNetworking__TestSystem::GeoNetworkingReq& p_gn_req, params& p_param); + * \brief Send GeoNetworking message to the lower layers + * \param[in] p_gn_req The GeoNetworking message to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + void sendMsg(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingReq &p_gn_req, params &p_param); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual OCTETSTRING trigger_ac_event(OCTETSTRING &data, params ¶ms); + + const LibItsGeoNetworking__TypesAndValues::LongPosVector *get_lpv(const LibItsGeoNetworking__TypesAndValues::GN__Address &p_gn_address); + void start_beaconing(); + void start_beaconing(const LibItsGeoNetworking__TypesAndValues::GeoNetworkingPdu &p_beacon); + void stop_beaconing(); + void start_pass_beaconing(const LibItsGeoNetworking__TypesAndValues::BeaconHeader &p_beacon); + void stop_pass_beaconing(); + + int enable_secured_mode(const std::string &p_certificate_id, const boolean p_enforce_security = false); + int disable_secured_mode(); + +private: + void init(const std::string &p_type, const std::string &p_param); + void send_beacon(); + int build_geonetworking_pdu(OCTETSTRING &data, params ¶ms); + int build_secured_pdu(OCTETSTRING &data, params ¶ms); + int decode_basic_header(const OCTETSTRING &p_data, LibItsGeoNetworking__TypesAndValues::BasicHeader &p_basic_header); + int setup_secured_mode(); + +}; // End of class geonetworking_layer diff --git a/ccsrc/Protocols/GeoNetworking/geonetworking_layer_factory.hh b/ccsrc/Protocols/GeoNetworking/geonetworking_layer_factory.hh index dfbc55314ff37176b8bfcd9cccdfa20f3c2bd9ae..7a79acb4c152730cb3a8596cd19cb8d9dc875092 100644 --- a/ccsrc/Protocols/GeoNetworking/geonetworking_layer_factory.hh +++ b/ccsrc/Protocols/GeoNetworking/geonetworking_layer_factory.hh @@ -1,44 +1,44 @@ -/*! - * \file geonetworking_layer_factory.hh - * \brief Header file for ITS GeoNetworking protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "geonetworking_layer.hh" - -/*! - * \class udp_layer_factory - * \brief This class provides a factory class to create an udp_layer class instance - */ -class geonetworking_layer_factory : public layer_factory { - static geonetworking_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the udp_layer_factory class - * \remark The GeoNetworking layer identifier is GN - */ - -public: - geonetworking_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("GN", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new geonetworking_layer(p_type, p_param); }; -}; // End of class geonetworking_layer_factory +/*! + * \file geonetworking_layer_factory.hh + * \brief Header file for ITS GeoNetworking protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "geonetworking_layer.hh" + +/*! + * \class udp_layer_factory + * \brief This class provides a factory class to create an udp_layer class instance + */ +class geonetworking_layer_factory : public layer_factory { + static geonetworking_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the udp_layer_factory class + * \remark The GeoNetworking layer identifier is GN + */ + +public: + geonetworking_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("GN", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new geonetworking_layer(p_type, p_param); }; +}; // End of class geonetworking_layer_factory diff --git a/ccsrc/Protocols/GeoNetworking/geonetworking_types.hh b/ccsrc/Protocols/GeoNetworking/geonetworking_types.hh index 9e9a3cfaa0c41ffa0ebc418320bc252e9d44797c..406cfe32dace489ddf5c4ff67ca8e6fc1e6116d9 100644 --- a/ccsrc/Protocols/GeoNetworking/geonetworking_types.hh +++ b/ccsrc/Protocols/GeoNetworking/geonetworking_types.hh @@ -1,15 +1,15 @@ -/*! - * \file geonetworking_types.hh - * \brief Header file for TITAN GeoNetworking types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsGeoNetworking_TestSystem.hh" -#include "LibItsGeoNetworking_TypesAndValues.hh" +/*! + * \file geonetworking_types.hh + * \brief Header file for TITAN GeoNetworking types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsGeoNetworking_TestSystem.hh" +#include "LibItsGeoNetworking_TypesAndValues.hh" diff --git a/ccsrc/Protocols/GeoNetworking/location_table.cc b/ccsrc/Protocols/GeoNetworking/location_table.cc index c1892f031a2d89024631e8959a4fe88d81b6c4e5..46a247a12fe216d0dd85abcd4f6a005c24c58b06 100644 --- a/ccsrc/Protocols/GeoNetworking/location_table.cc +++ b/ccsrc/Protocols/GeoNetworking/location_table.cc @@ -1,56 +1,56 @@ -#include "location_table.hh" - -#include "geonetworking_types.hh" - -#include "loggers.hh" - -using namespace LibItsGeoNetworking__TypesAndValues; - -void location_table::add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector &p_long_pos_vector) { - loggers::get_instance().log_msg(">>> location_table::add_entry:", p_long_pos_vector); - - std::map>::const_iterator it = - _entries_by_mids.find(std::string(oct2str(p_long_pos_vector.gnAddr().mid()))); - if (it == _entries_by_mids.cend()) { // Not found - // Add it - loggers::get_instance().log_to_hexa("location_table::add_entry: Create new entry: ", p_long_pos_vector.gnAddr().mid()); - std::shared_ptr lpv(new LibItsGeoNetworking__TypesAndValues::LongPosVector(p_long_pos_vector)); - _entries_by_times.insert(std::pair>( - static_cast(p_long_pos_vector.timestamp__().get_long_long_val()), lpv)); - _entries_by_mids.insert(std::pair>( - std::string(oct2str(p_long_pos_vector.gnAddr().mid())), lpv)); - } else { - // Remove entry from _entries_by_times.insert - // TODO Update the timestamp - // Add new entry in _entries_by_times.insert - } -} // End of add_entry method - -const bool location_table::has_entry(const OCTETSTRING &p_mid) const { - loggers::get_instance().log_to_hexa(">>> location_table::has_entry: ", p_mid); - loggers::get_instance().log(">>> location_table::has_entry: l=%d", _entries_by_mids.size()); - // loggers::get_instance().log_to_hexa(">>> location_table::has_entry: ", _entries_by_mids[0]); - - std::map>::const_iterator it = - _entries_by_mids.find(std::string(oct2str(p_mid))); - return (it != _entries_by_mids.cend()); -} - -const LibItsGeoNetworking__TypesAndValues::LongPosVector *location_table::get_entry(const OCTETSTRING &p_mid) const { - loggers::get_instance().log_to_hexa("location_table::get_entry: ", p_mid); - - // Sanity check - if (_entries_by_times.empty() || (p_mid.lengthof() != 6)) { - loggers::get_instance().warning("location_table::get_entry: Wrong parameters"); - return nullptr; - } - - std::map>::const_iterator it = - _entries_by_mids.find(std::string(oct2str(p_mid))); - if (it == _entries_by_mids.cend()) { // Not found - loggers::get_instance().warning("location_table::get_entry: Item not found"); - return nullptr; - } - - return it->second.get(); -} // End of get_entry method +#include "location_table.hh" + +#include "geonetworking_types.hh" + +#include "loggers.hh" + +using namespace LibItsGeoNetworking__TypesAndValues; + +void location_table::add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector &p_long_pos_vector) { + loggers::get_instance().log_msg(">>> location_table::add_entry:", p_long_pos_vector); + + std::map>::const_iterator it = + _entries_by_mids.find(std::string(oct2str(p_long_pos_vector.gnAddr().mid()))); + if (it == _entries_by_mids.cend()) { // Not found + // Add it + loggers::get_instance().log_to_hexa("location_table::add_entry: Create new entry: ", p_long_pos_vector.gnAddr().mid()); + std::shared_ptr lpv(new LibItsGeoNetworking__TypesAndValues::LongPosVector(p_long_pos_vector)); + _entries_by_times.insert(std::pair>( + static_cast(p_long_pos_vector.timestamp__().get_long_long_val()), lpv)); + _entries_by_mids.insert(std::pair>( + std::string(oct2str(p_long_pos_vector.gnAddr().mid())), lpv)); + } else { + // Remove entry from _entries_by_times.insert + // TODO Update the timestamp + // Add new entry in _entries_by_times.insert + } +} // End of add_entry method + +const bool location_table::has_entry(const OCTETSTRING &p_mid) const { + loggers::get_instance().log_to_hexa(">>> location_table::has_entry: ", p_mid); + loggers::get_instance().log(">>> location_table::has_entry: l=%d", _entries_by_mids.size()); + // loggers::get_instance().log_to_hexa(">>> location_table::has_entry: ", _entries_by_mids[0]); + + std::map>::const_iterator it = + _entries_by_mids.find(std::string(oct2str(p_mid))); + return (it != _entries_by_mids.cend()); +} + +const LibItsGeoNetworking__TypesAndValues::LongPosVector *location_table::get_entry(const OCTETSTRING &p_mid) const { + loggers::get_instance().log_to_hexa("location_table::get_entry: ", p_mid); + + // Sanity check + if (_entries_by_times.empty() || (p_mid.lengthof() != 6)) { + loggers::get_instance().warning("location_table::get_entry: Wrong parameters"); + return nullptr; + } + + std::map>::const_iterator it = + _entries_by_mids.find(std::string(oct2str(p_mid))); + if (it == _entries_by_mids.cend()) { // Not found + loggers::get_instance().warning("location_table::get_entry: Item not found"); + return nullptr; + } + + return it->second.get(); +} // End of get_entry method diff --git a/ccsrc/Protocols/GeoNetworking/location_table.hh b/ccsrc/Protocols/GeoNetworking/location_table.hh index 4fa83f11fb4cd692e9f1e34e150095fa80ff867b..693001134b82798b13c52705e45966779af8df68 100644 --- a/ccsrc/Protocols/GeoNetworking/location_table.hh +++ b/ccsrc/Protocols/GeoNetworking/location_table.hh @@ -1,78 +1,78 @@ -/*! - * \file location_table.hh - * \brief Header file for GeoNetworking location table definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include - -class OCTETSTRING; - -namespace LibItsGeoNetworking__TypesAndValues { - class LongPosVector; -} - -/*! - * \class location_table - * \brief This class provides description of GeoNetworking table - * \todo Add time expired removal procedure - * \todo Add reference to the GeoNetworking ETSI standard - */ -class location_table { - std::map> _entries_by_times; - std::map> _entries_by_mids; - -public: //! \publicsection - /*! - * \brief Default constructor - */ - explicit location_table() : _entries_by_times(), _entries_by_mids(){}; - /*! - * \brief Default destructor - */ - virtual ~location_table(){}; // std::shared_ptr provides memory free process - - /*! - * \fn const bool has_entry(const OCTETSTRING& p_mid) const; - * \brief Indicates if the GeoNetworking MID is present in the table - * \param[in] p_mid The GeoNetworking MID - * \return true on success, false otherwise - */ - const bool has_entry(const OCTETSTRING &p_mid) const; - /*! - * \fn void add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector& p_long_pos_vector); - * \brief Add a new item in the location table - * \param[in] p_long_pos_vector The new long position vector to add - */ - void add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector &p_long_pos_vector); - /*! - * \fn const LibItsGeoNetworking__TypesAndValues::LongPosVector* get_entry(const OCTETSTRING & p_mid) const; - * \brief Retrieve an item from the location table based on the GeoNetworking MID - * \param[in] p_mid The GeoNetworking MID - */ - const LibItsGeoNetworking__TypesAndValues::LongPosVector *get_entry(const OCTETSTRING &p_mid) const; - - /*! - * \inline - * \fn const bool empty() const; - * \brief Indicates if the table is empty - * \return true on success, false otherwise - */ - inline const bool empty() const { return _entries_by_mids.empty(); }; - /*! - * \inline - * \fn void reset(); - * \brief Purge the location table - */ - inline void reset() { - _entries_by_mids.clear(); - _entries_by_times.clear(); - }; -}; // End of class location_table +/*! + * \file location_table.hh + * \brief Header file for GeoNetworking location table definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include + +class OCTETSTRING; + +namespace LibItsGeoNetworking__TypesAndValues { + class LongPosVector; +} + +/*! + * \class location_table + * \brief This class provides description of GeoNetworking table + * \todo Add time expired removal procedure + * \todo Add reference to the GeoNetworking ETSI standard + */ +class location_table { + std::map> _entries_by_times; + std::map> _entries_by_mids; + +public: //! \publicsection + /*! + * \brief Default constructor + */ + explicit location_table() : _entries_by_times(), _entries_by_mids(){}; + /*! + * \brief Default destructor + */ + virtual ~location_table(){}; // std::shared_ptr provides memory free process + + /*! + * \fn const bool has_entry(const OCTETSTRING& p_mid) const; + * \brief Indicates if the GeoNetworking MID is present in the table + * \param[in] p_mid The GeoNetworking MID + * \return true on success, false otherwise + */ + const bool has_entry(const OCTETSTRING &p_mid) const; + /*! + * \fn void add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector& p_long_pos_vector); + * \brief Add a new item in the location table + * \param[in] p_long_pos_vector The new long position vector to add + */ + void add_entry(const LibItsGeoNetworking__TypesAndValues::LongPosVector &p_long_pos_vector); + /*! + * \fn const LibItsGeoNetworking__TypesAndValues::LongPosVector* get_entry(const OCTETSTRING & p_mid) const; + * \brief Retrieve an item from the location table based on the GeoNetworking MID + * \param[in] p_mid The GeoNetworking MID + */ + const LibItsGeoNetworking__TypesAndValues::LongPosVector *get_entry(const OCTETSTRING &p_mid) const; + + /*! + * \inline + * \fn const bool empty() const; + * \brief Indicates if the table is empty + * \return true on success, false otherwise + */ + inline const bool empty() const { return _entries_by_mids.empty(); }; + /*! + * \inline + * \fn void reset(); + * \brief Purge the location table + */ + inline void reset() { + _entries_by_mids.clear(); + _entries_by_times.clear(); + }; +}; // End of class location_table diff --git a/ccsrc/Protocols/GeoNetworking/module.mk b/ccsrc/Protocols/GeoNetworking/module.mk index 889d69c296fc478f7529507208dfc609653e33f5..b9c72ec8b6dc3ea8759a30d594d5fa1325452899 100644 --- a/ccsrc/Protocols/GeoNetworking/module.mk +++ b/ccsrc/Protocols/GeoNetworking/module.mk @@ -1,3 +1,3 @@ -sources := geonetworking_codec.cc geonetworking_layer.cc location_table.cc -includes := . - +sources := geonetworking_codec.cc geonetworking_layer.cc location_table.cc +includes := . + diff --git a/ccsrc/Protocols/Http/http_codec.cc b/ccsrc/Protocols/Http/http_codec.cc index e4c09d1aa66f766efae9be2d90693f7e16e25fe7..cba5b119c68061f04be51df92fd95add34b744a7 100644 --- a/ccsrc/Protocols/Http/http_codec.cc +++ b/ccsrc/Protocols/Http/http_codec.cc @@ -1,740 +1,740 @@ -#include -#include -#include - -#include "codec_stack_builder.hh" - -#include "http_codec.hh" - -#include "loggers.hh" - -#include "LibItsHttp_MessageBodyTypes.hh" -#include "LibItsHttp_TypesAndValues.hh" -#include "LibItsHttp_XmlMessageBodyTypes.hh" - -#include "http_etsi_ieee1609dot2_codec.hh" - -int http_codec::encode(const LibItsHttp__TypesAndValues::HttpMessage &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> http_codec::encode: ", (const Base_Type &)msg); - loggers::get_instance().log(">>> http_codec::encode: %p", this); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - - _ec.reset(); - - int result; - if (msg.ischosen(LibItsHttp__TypesAndValues::HttpMessage::ALT_request)) { - result = encode_request(msg.request(), encoding_buffer); - } else if (msg.ischosen(LibItsHttp__TypesAndValues::HttpMessage::ALT_response)) { - result = encode_response(msg.response(), encoding_buffer); - } else { - loggers::get_instance().warning("http_codec::encode: Unbound HttpMessage"); - return -1; - } - - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - - loggers::get_instance().log_msg("<<< http_codec::encode: data=", data); - return result; -} - -int http_codec::decode(const OCTETSTRING &data, LibItsHttp__TypesAndValues::HttpMessage &msg, params *params) { - loggers::get_instance().log_msg(">>> http_codec::decode: data=", data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - loggers::get_instance().log_to_hexa("http_codec::decode: decoding_buffer=", decoding_buffer); - - _dc.reset(); - - _params = params; - - // Get the first line (e.g. HTTP/1.1 302 Found or POST / HTTP/1.1) - CHARSTRING message_id; - if (get_line(decoding_buffer, message_id) == -1) { - return -1; - } - loggers::get_instance().log_msg("http_codec::decode: message_id: ", message_id); - // Extract parameters - try { - std::string str(static_cast(message_id)); - std::regex rgx("\\s*(\\w+)/"); - std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); - std::smatch m = *begin; - loggers::get_instance().log("http_codec::decode: %d - %s", m.size(), m[0].str().c_str()); - if (m[0].str().compare("HTTP/") == 0) { // HTTP response - LibItsHttp__TypesAndValues::Response response; - std::regex rgx("\\s*HTTP/(\\d+)\\.(\\d+)\\s+(\\d+)\\s+([\\w\\s\\t\\v\\f]+)*"); - std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); - std::smatch m = *begin; - loggers::get_instance().log("http_codec::decode: Process response: %d", m.size()); - if (m.size() != 5) { - loggers::get_instance().error("http_codec::decode: Unsupported tag"); - return -1; - } - response.version__major() = std::stoi(m[1].str().c_str()); - response.version__minor() = std::stoi(m[2].str().c_str()); - response.statuscode() = std::stoi(m[3].str().c_str()); - response.statustext() = CHARSTRING(m[4].str().c_str()); - LibItsHttp__TypesAndValues::Headers headers; - std::string content_type; - decode_headers(decoding_buffer, headers, content_type); - response.header() = headers; - loggers::get_instance().log_to_hexa("Before decoding Body: ", decoding_buffer); - LibItsHttp__MessageBodyTypes::HttpMessageBody body; - if (decode_body(decoding_buffer, body, content_type) == -1) { - response.body().set_to_omit(); - } else { - response.body() = OPTIONAL(body); - } - msg.response() = response; - } else { // HTTP request - LibItsHttp__TypesAndValues::Request request; - std::regex rgx("\\s*(\\w+)\\s+(.+)\\s+HTTP/(\\d)\\.(\\d)"); - std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); - std::smatch m = *begin; - if (m.size() != 5) { - loggers::get_instance().error("http_codec::decode: Unsupported tag"); - return -1; - } - request.method() = CHARSTRING(m[1].str().c_str()); - request.uri() = CHARSTRING(m[2].str().c_str()); - request.version__major() = std::stoi(m[3].str().c_str()); - request.version__minor() = std::stoi(m[4].str().c_str()); - LibItsHttp__TypesAndValues::Headers headers; - std::string content_type; - decode_headers(decoding_buffer, headers, content_type); - request.header() = headers; - OPTIONAL body; - body.set_to_omit(); - if (decode_body(decoding_buffer, body, content_type) == -1) { - request.body().set_to_omit(); - } else { - request.body() = body; - } - msg.request() = request; - } - - loggers::get_instance().log_msg("<<< http_codec::decode: ", (const Base_Type &)msg); - return 0; - } catch (const std::logic_error &e) { - return -1; - } -} - -int http_codec::encode_request(const LibItsHttp__TypesAndValues::Request &p_request, TTCN_Buffer &p_encoding_buffer) { - loggers::get_instance().log_msg(">>> http_codec::encode_request: ", (const Base_Type &)p_request); - - // Encode generic part - p_encoding_buffer.put_cs(p_request.method()); - p_encoding_buffer.put_c(' '); - p_encoding_buffer.put_cs(p_request.uri()); - p_encoding_buffer.put_cs(" HTTP/"); - p_encoding_buffer.put_cs(int2str(p_request.version__major())); - p_encoding_buffer.put_c('.'); - p_encoding_buffer.put_cs(int2str(p_request.version__minor())); - p_encoding_buffer.put_cs("\r\n"); - - // Encode headers excepeted the Content-Length - const LibItsHttp__TypesAndValues::Headers &headers = p_request.header(); - std::string content_type; - for (int i = 0; i < headers.size_of(); i++) { - const LibItsHttp__TypesAndValues::Header &header = headers[i]; - loggers::get_instance().log_msg("http_codec::encode_request: Processing header ", header.header__name()); - if (std::string(static_cast(header.header__name())).compare("Content-Length") == 0) { // Skip it, processed later - loggers::get_instance().log("http_codec::encode_request: Skip it"); - continue; - } else { - p_encoding_buffer.put_cs(header.header__name()); - p_encoding_buffer.put_cs(": "); - const OPTIONAL &o = header.header__value(); - if (o.ispresent()) { - const LibItsHttp__TypesAndValues::charstring__list &v = dynamic_cast &>(o); - if (v.size_of() > 0) { - loggers::get_instance().log_msg("http_codec::encode_request: Processing value ", v[0]); - if (std::string(static_cast(header.header__name())).compare("Content-Type") == 0) { // Store it for HTTP body payload encoding - loggers::get_instance().log("http_codec::encode_request: Storing Content-Type"); - int j = 0; - while (j < v.size_of()) { - content_type += v[j++]; - } // End of 'while' statement - } - p_encoding_buffer.put_cs(v[0]); - int j = 1; - while (j < v.size_of()) { - p_encoding_buffer.put_cs(", "); - loggers::get_instance().log_msg("http_codec::encode_request: Processing value ", v[j]); - p_encoding_buffer.put_cs(v[j++]); - } // End of 'while' statement - } - } // else, do not include it - } - p_encoding_buffer.put_cs("\r\n"); - } // End of 'for' statement - - // Encode message body - const OPTIONAL &v = p_request.body(); - OCTETSTRING os; - if (v.ispresent()) { - const LibItsHttp__MessageBodyTypes::HttpMessageBody &body = static_cast(*v.get_opt_value()); - loggers::get_instance().log_msg("http_codec::encode_request: body: ", body); - if (encode_body(body, os, content_type) == -1) { - loggers::get_instance().warning("http_codec::encode_request: Failed to encode HTTP body"); - _ec.length = 0; - _ec.is_content_length_present = 0x00; - } else { - _ec.length = os.lengthof(); - _ec.is_content_length_present = 0x01; - } - loggers::get_instance().log("http_codec::encode_request: length=%d", _ec.length); - } else { - loggers::get_instance().log("http_codec::encode_request: HTTP body field not present"); - _ec.length = 0; - _ec.is_content_length_present = 0x00; - } - - // Encode Content-Length header - p_encoding_buffer.put_cs("Content-Length: "); - if (_ec.length != 0) { - loggers::get_instance().log("http_codec::encode_request: Content-Length: %s", - static_cast(int2str(_ec.length + 2 /*Stand for the last CRLF*/))); - p_encoding_buffer.put_cs(static_cast(int2str(_ec.length))); - _ec.is_content_length_present = 0x01; - } else { - p_encoding_buffer.put_cs("0"); - _ec.is_content_length_present = 0x00; - } - loggers::get_instance().log("http_codec::encode_request: Content-Length: %d - %x", _ec.length, _ec.is_content_length_present); - p_encoding_buffer.put_cs("\r\n"); - - // Add message body - p_encoding_buffer.put_cs("\r\n"); - if (_ec.is_content_length_present == 0x01) { - loggers::get_instance().log_msg("http_codec::encode_request: Add body ", os); - p_encoding_buffer.put_os(os); - // p_encoding_buffer.put_cs("\r\n"); - } - - loggers::get_instance().log_to_hexa("<<< http_codec::encode_request: ", p_encoding_buffer); - return 0; -} - -int http_codec::encode_response(const LibItsHttp__TypesAndValues::Response &p_response, TTCN_Buffer &p_encoding_buffer) { - loggers::get_instance().log_msg(">>> http_codec::encode_response: ", (const Base_Type &)p_response); - - // Encode generic part - p_encoding_buffer.put_cs("HTTP/"); - p_encoding_buffer.put_cs(int2str(p_response.version__major())); - p_encoding_buffer.put_c('.'); - p_encoding_buffer.put_cs(int2str(p_response.version__minor())); - p_encoding_buffer.put_cs(" "); - p_encoding_buffer.put_cs(int2str(p_response.statuscode())); - p_encoding_buffer.put_cs(" "); - if (p_response.statustext().lengthof() != 0) { - p_encoding_buffer.put_cs(p_response.statustext()); - } - p_encoding_buffer.put_cs("\r\n"); - - // Encode headers excepeted the Content-Length - const LibItsHttp__TypesAndValues::Headers &headers = p_response.header(); - std::string content_type; - for (int i = 0; i < headers.size_of(); i++) { - const LibItsHttp__TypesAndValues::Header &header = headers[i]; - loggers::get_instance().log_msg("http_codec::encode_response: Processing header ", header.header__name()); - p_encoding_buffer.put_cs(header.header__name()); - p_encoding_buffer.put_cs(": "); - if (std::string(static_cast(header.header__name())).compare("Content-Length") == 0) { - continue; - } else { - const OPTIONAL &o = header.header__value(); - if (o.ispresent()) { - const LibItsHttp__TypesAndValues::charstring__list &v = dynamic_cast &>(o); - if (v.size_of() > 0) { - loggers::get_instance().log_msg("http_codec::encode_response: Processing value ", v[0]); - if (std::string(static_cast(header.header__name())).compare("Content-Type") == 0) { // Store it for HTTP body payload encoding - loggers::get_instance().log("http_codec::encode_response: Storing Content-Type"); - int j = 0; - while (j < v.size_of()) { - content_type += v[j++]; - } // End of 'while' statement - } - p_encoding_buffer.put_cs(v[0]); - int j = 1; - while (j < v.size_of()) { - p_encoding_buffer.put_cs(", "); - loggers::get_instance().log_msg("http_codec::encode_response: Processing value ", v[j]); - p_encoding_buffer.put_cs(v[j++]); - j += 1; - } // End of 'while' statement - } - } // else, do not include it - } - p_encoding_buffer.put_cs("\r\n"); - } // End of 'for' statement - - // Encode message body - const OPTIONAL &v = p_response.body(); - OCTETSTRING os; - if (v.ispresent()) { - const LibItsHttp__MessageBodyTypes::HttpMessageBody &body = static_cast(*v.get_opt_value()); - loggers::get_instance().log_msg("http_codec::encode_response: body: ", body); - if (encode_body(body, os, content_type) == -1) { - _ec.length = 0; - _ec.is_content_length_present = 0x00; - } else { - _ec.length = os.lengthof(); - _ec.is_content_length_present = 0x01; - } - loggers::get_instance().log("http_codec::encode_response: length=%d", _ec.length); - } else { - loggers::get_instance().log("http_codec::encode_response: HTTP body field not present"); - _ec.length = 0; - _ec.is_content_length_present = 0x00; - } - - // Encode Content-Length header - p_encoding_buffer.put_cs("Content-Length: "); - if (_ec.length != 0) { - loggers::get_instance().log("http_codec::encode_request: Content-Length: %s", - static_cast(int2str(_ec.length + 2 /*Stand for the last CRLF*/))); - p_encoding_buffer.put_cs(static_cast(int2str(_ec.length))); - _ec.is_content_length_present = 0x01; - } else { - p_encoding_buffer.put_cs("0"); - _ec.is_content_length_present = 0x00; - } - loggers::get_instance().log("http_codec::encode_request: Content-Length: %d - %x", _ec.length, _ec.is_content_length_present); - p_encoding_buffer.put_cs("\r\n"); - - // Add message body - p_encoding_buffer.put_cs("\r\n"); - if (_ec.is_content_length_present == 0x01) { - loggers::get_instance().log_msg("http_codec::encode_request: Add body ", os); - p_encoding_buffer.put_os(os); - // p_encoding_buffer.put_cs("\r\n"); - } - - loggers::get_instance().log_to_hexa("<<< http_codec::encode_response: ", p_encoding_buffer); - return 0; -} - -int http_codec::decode_headers(TTCN_Buffer &decoding_buffer, LibItsHttp__TypesAndValues::Headers &headers, std::string &p_content_type) { - loggers::get_instance().log(">>> http_codec::decode_headers"); - loggers::get_instance().log_to_hexa("http_codec::decode_headers", decoding_buffer); - - CHARSTRING cstr; - int i = 0; - while (true) { - switch (get_line(decoding_buffer, cstr, true)) { - case 0: { - loggers::get_instance().log_msg("http_codec::decode_headers: ", cstr); - LibItsHttp__TypesAndValues::Header header; - if (decode_header(cstr, header) == -1) { - loggers::get_instance().warning("http_codec::decode_headers: Failed to decode header %s", static_cast(cstr)); - return -1; - } - headers[i++] = header; - if (std::string(static_cast(header.header__name())).compare("Content-Type") == 0) { - if (header.header__value().is_present() != 0) { - const PreGenRecordOf::PREGEN__RECORD__OF__CHARSTRING &l = - static_cast(*header.header__value().get_opt_value()); - p_content_type = static_cast(l[0]); - } else { - p_content_type = ""; - } - } - } break; - case 1: - loggers::get_instance().log_msg("<<< http_codec::decode_headers: ", headers); - return 0; - case -1: - loggers::get_instance().warning("http_codec::decode_headers: Failed to decode headers"); - return -1; - } // End of 'switch' statement - } // End of 'while' statement -} - -int http_codec::decode_header(CHARSTRING &header_line, LibItsHttp__TypesAndValues::Header &header) { - loggers::get_instance().log_msg(">>> http_codec::decode_header", header_line); - - try { - std::string str(static_cast(header_line)); - std::regex rgx("([0-9a-zA-Z-]+)\\:\\s+(.+)(,(.+))*"); - std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); - std::smatch m = *begin; - if (m.size() < 5) { - loggers::get_instance().warning("http_codec::decode_header: Failed to decode header %s", str.c_str()); - return -1; - } - loggers::get_instance().log("http_codec::decode_header: %d", m.size()); - header.header__name() = CHARSTRING(m[1].str().c_str()); - LibItsHttp__TypesAndValues::charstring__list v; - for (unsigned int j = 0; j < m.size(); j++) { - if (m[j + 2].str().length() == 0) { - break; - } - v[j] = CHARSTRING(m[j + 2].str().c_str()); - } // End of 'for' statement - header.header__value() = OPTIONAL(v); - - if (m[1].str().compare("Content-Length") == 0) { - // Save the the body length - loggers::get_instance().log("http_codec::decode_header: decoded Content-Length %s", m[2].str().c_str()); - _dc.length = std::stoi(m[2].str()); - } else if (m[1].str().compare("Transfer-Encoding") == 0) { - if (m[2].str().find("chunked") != std::string::npos) { - _dc.chunked = true; - loggers::get_instance().log("http_codec::decode_header: decoded Transfer-Encoding %x", _dc.chunked); - } - } - - return 0; - } catch (const std::logic_error &e) { - return -1; - } -} - -int http_codec::encode_body(const LibItsHttp__MessageBodyTypes::HttpMessageBody &p_message_body, OCTETSTRING &p_encoding_buffer, - const std::string &p_content_type) { - loggers::get_instance().log_msg(">>> http_codec::encode_body: ", (const Base_Type &)p_message_body); - - // Sanity check - if (p_content_type.empty()) { - loggers::get_instance().warning("http_codec::encode_body: Failed to select a codec for HTTP body payload"); - return -1; - } - - if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_binary__body)) { - const LibItsHttp__BinaryMessageBodyTypes::BinaryBody &binary_body = p_message_body.binary__body(); - if (binary_body.ischosen(LibItsHttp__BinaryMessageBodyTypes::BinaryBody::ALT_raw)) { - p_encoding_buffer = OCTETSTRING(binary_body.raw().lengthof(), (unsigned char *)static_cast(binary_body.raw())); - } else { - std::map>>::const_iterator it; - bool processed = false; - if (p_content_type.find("x-its") != std::string::npos) { - loggers::get_instance().log("http_codec::encode_body: Find x-its"); - it = _codecs.find("http_its"); // TODO Use params - if (it != _codecs.cend()) { - 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 - processed = true; - } - } // TODO Add new HTTP message codec here - if (!processed) { - loggers::get_instance().warning("http_codec::encode_body: Unsupported HTTP codec, use raw field as default"); - p_encoding_buffer = OCTETSTRING(0, nullptr); - } - } - } else if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_html__body)) { - p_encoding_buffer = OCTETSTRING(p_message_body.html__body().lengthof(), (unsigned char *)static_cast(p_message_body.html__body())); - } else if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_text__body)) { - p_encoding_buffer = OCTETSTRING(p_message_body.text__body().lengthof(), (unsigned char *)static_cast(p_message_body.text__body())); - } else if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_xml__body)) { - const LibItsHttp__XmlMessageBodyTypes::XmlBody &xml_body = p_message_body.xml__body(); - if (xml_body.ischosen(LibItsHttp__XmlMessageBodyTypes::XmlBody::ALT_raw)) { - p_encoding_buffer = OCTETSTRING(xml_body.raw().lengthof(), (unsigned char *)static_cast(xml_body.raw())); - } else { - std::map>>::const_iterator it; - bool processed = false; - loggers::get_instance().log("http_codec::encode_body: Content-Type:'%s'", p_content_type.c_str()); - if (p_content_type.find("held") != std::string::npos) { - it = _codecs.find("held"); // TODO Use params - if (it != _codecs.cend()) { - loggers::get_instance().log("http_codec::encode_body: Call 'held_codec'"); - _codecs["held"]->encode((Record_Type &)xml_body, p_encoding_buffer); // TODO Use params - processed = true; - } - } else if (p_content_type.find("lost") != std::string::npos) { - it = _codecs.find("lost"); // TODO Use params - if (it != _codecs.cend()) { - loggers::get_instance().log("http_codec::encode_body: Call 'lost_codec'"); - _codecs["lost"]->encode((Record_Type &)xml_body, p_encoding_buffer); // TODO Use params - processed = true; - } - } // TODO Add new HTTP message codec here - if (!processed) { - loggers::get_instance().warning("http_codec::encode_body: Unsupported HTTP codec, use raw field as default"); - p_encoding_buffer = OCTETSTRING(0, nullptr); - } - } - } else { - loggers::get_instance().warning("http_codec::encode_body: Failed to encode HTTP message body"); - return -1; - } - loggers::get_instance().log_msg("http_codec::encode_body: HTTP message ", p_encoding_buffer); - _ec.length = p_encoding_buffer.lengthof(); - loggers::get_instance().log("http_codec::encode_body: HTTP message length: %d", _ec.length); - - return 0; -} - -int http_codec::decode_body(TTCN_Buffer &decoding_buffer, LibItsHttp__MessageBodyTypes::HttpMessageBody &message_body, const std::string &p_content_type) { - loggers::get_instance().log(">>> http_codec::decode_body"); - loggers::get_instance().log_to_hexa("http_codec::decode_body", decoding_buffer); - loggers::get_instance().log("http_codec::decode_body: # of codecs=%d - %p", _codecs.size(), this); - loggers::get_instance().log("http_codec::decode_body: Content-Type=%s", p_content_type.c_str()); - - // Sanity checks - if (decoding_buffer.get_len() - decoding_buffer.get_pos() <= 0) { - return -1; - } - /* TODO Uncommentif (p_content_type.empty()) { - loggers::get_instance().warning("http_codec::encode_body: Failed to select a codec for HTTP body payload"); - return -1; - }*/ - - 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); - - // 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; - if (_dc.length != 0) { - const unsigned char *p = static_cast(s); - if ((unsigned int)s.lengthof() <= _dc.length) { - body = OCTETSTRING(s.lengthof(), p); - } else { - body = OCTETSTRING(_dc.length, p); - } - } else { - loggers::get_instance().warning("http_codec::decode_body: No Conten-Length header, process all remaining bytes"); - body = s; - } - loggers::get_instance().log_msg("http_codec::decode_body: Aligned body=", body); - loggers::get_instance().log("http_codec::decode_body: body length=%d", body.lengthof()); - /* TODO To be removed - // Remove CRLF if any - int counter = 0; - if ((body[body.lengthof() - 1].get_octet() == 0x0d) || (body[body.lengthof() - 1].get_octet() == 0x0a)) { - counter += 1; - if ((body[body.lengthof() - 2].get_octet() == 0x0d) || (body[body.lengthof() - 2].get_octet() == 0x0a)) { - counter += 1; - } - } - loggers::get_instance().log("http_codec::decode_body: counter=%d", counter); - body = OCTETSTRING(body.lengthof() - counter, static_cast(body)); - */ - if (_dc.chunked) { - int counter = 0; - int prev = 0; - OCTETSTRING os(0, nullptr); - do { - while (counter < body.lengthof()) { // Extract the size of the chunk \r[\n] - if ((body[counter].get_octet() == '\r') || (body[counter].get_octet() == '\n')) { - break; - } - counter += 1; - } // End of 'while' statement - loggers::get_instance().log("http_codec::decode_body: Chunked(0): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); - if (counter < body.lengthof()) { - int idx = counter - prev; - OCTETSTRING trunk(idx, static_cast(body)); - loggers::get_instance().log_msg("http_codec::decode_body: trunk: ", trunk); - std::string str((const char *)static_cast(trunk), idx); - loggers::get_instance().log("http_codec::decode_body: str: '%s'", str.c_str()); - int len = std::stoi(str, nullptr, 16); // converter::get_instance().string_to_int(str); - loggers::get_instance().log("http_codec::decode_body: Chunk len: %d", len); - while (counter < body.lengthof() && ((body[counter].get_octet() == '\r') || (body[counter].get_octet() == '\n'))) { // Skip additional \n - counter += 1; - } // End of 'while' statement - if (counter < body.lengthof()) { - loggers::get_instance().log("http_codec::decode_body: Chunked (1): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); - os += OCTETSTRING(len, counter + static_cast(body)); - loggers::get_instance().log_msg("http_codec::decode_body: os=", os); - counter += len; - loggers::get_instance().log("http_codec::decode_body: Chunked: %02x %02x %02x", body[counter].get_octet(), body[counter + 1].get_octet(), - body[counter + 2].get_octet()); - loggers::get_instance().log("http_codec::decode_body: Chunked (2): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); - while (counter < body.lengthof() && ((body[counter].get_octet() == '\r') || (body[counter].get_octet() == '\n'))) { // Skip additional \n - counter += 1; - } // End of 'while' statement - prev = counter; - loggers::get_instance().log("http_codec::decode_body: Chunked (3): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); - } - } - } while (counter < body.lengthof()); // Process next chunk if any - body = os; - loggers::get_instance().log_msg("http_codec::decode_body: Finalised body=", body); - } - // Check if HTTP message body contains binary characters - for (int i = 0; i < body.lengthof(); i++) { - unsigned char c = body[i].get_octet(); - if (!std::isprint(c) && !std::isspace(c) && !std::ispunct(c)) { - loggers::get_instance().log("http_codec::decode_body: Byte #%d is not printable: 0x%02x", i, body[i].get_octet()); - _dc.is_binary = 0x01; - break; - } - } // End of 'for' statement - loggers::get_instance().log("http_codec::decode_body: Binary mode: %x", _dc.is_binary); - LibItsHttp__MessageBodyTypes::HttpMessageBody v; - if (_dc.is_binary == 0x01) { - LibItsHttp__BinaryMessageBodyTypes::BinaryBody binary_body; - std::map>>::const_iterator it; - bool processed = false; - // TODO To be refined adding a string identifier to check which codec to use. E.g. held_code.id() returns "xmlns=\"urn:ietf:params:xml:ns:geopriv:held\">" - if (p_content_type.find("x-its") != std::string::npos) { - loggers::get_instance().log("http_codec::decode_body: Find 'x-its'"); - it = _codecs.cbegin(); //_codecs.find("http_its"); - if (it != _codecs.cend()) { - /*** - FIXME: - This code generate a codedump, I don't undertsand the reason. - The same code works file for Ng112 HELD & LOST codec. Ununderstandable!!!! - ==> Use a patch - if (_codecs["http_its"].get() != nullptr) { - loggers::get_instance().log("http_codec::decode_body: Call 'http_etsi_ieee1609dot2_codec'"); - if (_codecs["http_its"]->decode(body, (Record_Type&)binary_body) == 0) { - processed = true; - } - }*/ - loggers::get_instance().log("http_codec::decode_body: Call '%s'", it->first.c_str()); - http_etsi_ieee1609dot2_codec *codec = new http_etsi_ieee1609dot2_codec(); - if (codec->decode(body, binary_body.ieee1609dot2__data()) == 0) { - message_body.binary__body() = binary_body; - processed = true; - } - delete codec; - } - } // TODO Add new HTTP message codec here - if (!processed) { - loggers::get_instance().warning("http_codec::decode_body: Unsupported HTTP codec, use raw field as default"); - binary_body.raw() = body; - message_body.binary__body() = binary_body; - } - } else { - // Convert into string - params p; - p["decode_str"] = std::string(static_cast(body), body.lengthof() + static_cast(body)); - loggers::get_instance().log("http_codec::decode_body: decode_str: %s", p["decode_str"].c_str()); - // Try to identify xml - if (p["decode_str"].find("" - if ((p["decode_str"].find("=\"urn:ietf:params:xml:ns:geopriv:held\"") != std::string::npos) || - (p["decode_str"].find("=\"urn:ietf:params:xml:ns:pidf\"") != std::string::npos)) { - loggers::get_instance().log("http_codec::decode_body: Find 'urn:ietf:params:xml:ns:geopriv:held'"); - if (_codecs["held"].get() != nullptr) { - loggers::get_instance().log("http_codec::decode_body: Call 'held_codec'"); - if (_codecs["held"]->decode(body, (Record_Type &)xml_body, &p) == -1) { - loggers::get_instance().warning("http_codec::decode_body: Failed to decode HELD message"); - xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - } else { - loggers::get_instance().log_msg("http_codec::decode_body: Decoded message:", xml_body); - message_body.xml__body() = xml_body; - } - } else { - loggers::get_instance().warning("http_codec::decode_body: No codec for HELD"); - xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - } - message_body.xml__body() = xml_body; - } else if (p["decode_str"].find("=\"urn:ietf:params:xml:ns:lost1\"") != std::string::npos) { - loggers::get_instance().log("http_codec::decode_body: Find 'urn:ietf:params:xml:ns:lost1'"); - if (_codecs["lost"].get() != nullptr) { - loggers::get_instance().log("http_codec::decode_body: Call 'lost_codec'"); - if (_codecs["lost"]->decode(body, (Record_Type &)xml_body, &p) == -1) { - loggers::get_instance().warning("http_codec::decode_body: Failed to decode LOST message"); - xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - } else { - loggers::get_instance().log_msg("http_codec::decode_body: Decoded message:", xml_body); - message_body.xml__body() = xml_body; - } - } else { - loggers::get_instance().warning("http_codec::decode_body: No codec for LOST"); - xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - } - message_body.xml__body() = xml_body; - } else { - loggers::get_instance().warning("http_codec::decode_body: No XML codec found"); - xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - message_body.xml__body() = xml_body; - } - } else if (p["decode_str"].find("") != std::string::npos) { // Try to identify HTML - loggers::get_instance().log("http_codec::decode_body: Find html message"); - LibItsHttp__MessageBodyTypes::HtmlBody html_body; - message_body.html__body() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - } else { - loggers::get_instance().log("http_codec::decode_body: Use textBdy as default"); - LibItsHttp__MessageBodyTypes::TextBody text_body; - message_body.text__body() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); - } - } - - return 0; -} - -int http_codec::get_line(TTCN_Buffer &buffer, CHARSTRING &to, const bool concatenate_header_lines) { - unsigned int i = 0; - const unsigned char *cc_to = buffer.get_read_data(); - - // Sanity checks - if (buffer.get_read_len() == 0) { - return -1; - } - - while (true) { - // Skip spaces, and empty lines - for (; i < buffer.get_read_len() && cc_to[i] != '\0' && cc_to[i] != '\r' && cc_to[i] != '\n'; i++) - ; - if (i >= buffer.get_read_len()) { // No more characters to process - to = CHARSTRING(""); - return -1; - } else if (cc_to[i] == '\n') { // New line found, we don't care is '\r' is missing - if ((i > 0) && ((i + 1) < buffer.get_read_len()) && concatenate_header_lines && ((cc_to[i + 1] == ' ') || (cc_to[i + 1] == '\t'))) { - i += 1; // Skip it - } else { - to = CHARSTRING(i, (const char *)cc_to); - buffer.set_pos(buffer.get_pos() + i + 1); - return i == 0 ? 1 : 0; - } - } else { - if ((i + 1) < buffer.get_read_len() && cc_to[i + 1] != '\n') { - return -1; - } else if (i > 0 && (i + 2) < buffer.get_read_len() && concatenate_header_lines && (cc_to[i + 2] == ' ' || cc_to[i + 2] == '\t')) { - i += 2; - } else { - to = CHARSTRING(i, (const char *)cc_to); - buffer.set_pos(buffer.get_pos() + i + 2); - return i == 0 ? 1 : 0; - } - } - } // End of 'while' statement -} - -void http_codec::set_payload_codecs(const std::string &p_codecs) { - loggers::get_instance().log(">>> http_codec::set_payload_codecs: %s", p_codecs.c_str()); - - // Sanity check - if (p_codecs.length() == 0) { - return; - } - - // Extract codecs - try { - std::regex rgx("(\\w+):(\\w+)(;(\\w+):(\\w+))*"); - std::sregex_iterator begin(p_codecs.cbegin(), p_codecs.cend(), rgx); - std::sregex_iterator end = std::sregex_iterator(); - // E.g. 9 - xml - :held_codec - held_codec - ;html:html_codec - html:html_codec - html - :html_codec - html_codec - for (std::sregex_iterator it = begin; it != end; ++it) { - std::smatch m = *it; - loggers::get_instance().log("http_codec::set_payload_codecs: %d - %s - %s - %s - %s - %s - %s - %s - %s", m.size(), m[1].str().c_str(), - m[2].str().c_str(), m[3].str().c_str(), m[4].str().c_str(), m[5].str().c_str(), m[6].str().c_str(), m[7].str().c_str(), - m[8].str().c_str()); - for (unsigned int j = 1; j < m.size() - 1; j += 3) { // Exclude m[0] - loggers::get_instance().log("http_codec::set_payload_codecs: insert (%s, %s), j = %d", m[j].str().c_str(), m[j + 1].str().c_str(), j); - if (m[j].str().empty()) { - break; - } - std::string key(m[j].str()); - loggers::get_instance().log("http_codec::set_payload_codecs: Add codec %s", key.c_str()); - _codecs.insert( - std::make_pair(key, std::unique_ptr>(codec_stack_builder::get_instance()->get_codec(m[j + 1].str().c_str())))); - } // End of 'for' statement - } // End of 'for' statement - loggers::get_instance().log("http_codec::set_payload_codecs: _codecs length=%d - %p", _codecs.size(), this); - } catch (const std::logic_error &e) { - loggers::get_instance().warning("http_codec::set_payload_codecs: std::logic_error: %s", e.what()); - _codecs.clear(); - } -} +#include +#include +#include + +#include "codec_stack_builder.hh" + +#include "http_codec.hh" + +#include "loggers.hh" + +#include "LibItsHttp_MessageBodyTypes.hh" +#include "LibItsHttp_TypesAndValues.hh" +#include "LibItsHttp_XmlMessageBodyTypes.hh" + +#include "http_etsi_ieee1609dot2_codec.hh" + +int http_codec::encode(const LibItsHttp__TypesAndValues::HttpMessage &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> http_codec::encode: ", (const Base_Type &)msg); + loggers::get_instance().log(">>> http_codec::encode: %p", this); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + + _ec.reset(); + + int result; + if (msg.ischosen(LibItsHttp__TypesAndValues::HttpMessage::ALT_request)) { + result = encode_request(msg.request(), encoding_buffer); + } else if (msg.ischosen(LibItsHttp__TypesAndValues::HttpMessage::ALT_response)) { + result = encode_response(msg.response(), encoding_buffer); + } else { + loggers::get_instance().warning("http_codec::encode: Unbound HttpMessage"); + return -1; + } + + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + + loggers::get_instance().log_msg("<<< http_codec::encode: data=", data); + return result; +} + +int http_codec::decode(const OCTETSTRING &data, LibItsHttp__TypesAndValues::HttpMessage &msg, params *params) { + loggers::get_instance().log_msg(">>> http_codec::decode: data=", data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + loggers::get_instance().log_to_hexa("http_codec::decode: decoding_buffer=", decoding_buffer); + + _dc.reset(); + + _params = params; + + // Get the first line (e.g. HTTP/1.1 302 Found or POST / HTTP/1.1) + CHARSTRING message_id; + if (get_line(decoding_buffer, message_id) == -1) { + return -1; + } + loggers::get_instance().log_msg("http_codec::decode: message_id: ", message_id); + // Extract parameters + try { + std::string str(static_cast(message_id)); + std::regex rgx("\\s*(\\w+)/"); + std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); + std::smatch m = *begin; + loggers::get_instance().log("http_codec::decode: %d - %s", m.size(), m[0].str().c_str()); + if (m[0].str().compare("HTTP/") == 0) { // HTTP response + LibItsHttp__TypesAndValues::Response response; + std::regex rgx("\\s*HTTP/(\\d+)\\.(\\d+)\\s+(\\d+)\\s+([\\w\\s\\t\\v\\f]+)*"); + std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); + std::smatch m = *begin; + loggers::get_instance().log("http_codec::decode: Process response: %d", m.size()); + if (m.size() != 5) { + loggers::get_instance().error("http_codec::decode: Unsupported tag"); + return -1; + } + response.version__major() = std::stoi(m[1].str().c_str()); + response.version__minor() = std::stoi(m[2].str().c_str()); + response.statuscode() = std::stoi(m[3].str().c_str()); + response.statustext() = CHARSTRING(m[4].str().c_str()); + LibItsHttp__TypesAndValues::Headers headers; + std::string content_type; + decode_headers(decoding_buffer, headers, content_type); + response.header() = headers; + loggers::get_instance().log_to_hexa("Before decoding Body: ", decoding_buffer); + LibItsHttp__MessageBodyTypes::HttpMessageBody body; + if (decode_body(decoding_buffer, body, content_type) == -1) { + response.body().set_to_omit(); + } else { + response.body() = OPTIONAL(body); + } + msg.response() = response; + } else { // HTTP request + LibItsHttp__TypesAndValues::Request request; + std::regex rgx("\\s*(\\w+)\\s+(.+)\\s+HTTP/(\\d)\\.(\\d)"); + std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); + std::smatch m = *begin; + if (m.size() != 5) { + loggers::get_instance().error("http_codec::decode: Unsupported tag"); + return -1; + } + request.method() = CHARSTRING(m[1].str().c_str()); + request.uri() = CHARSTRING(m[2].str().c_str()); + request.version__major() = std::stoi(m[3].str().c_str()); + request.version__minor() = std::stoi(m[4].str().c_str()); + LibItsHttp__TypesAndValues::Headers headers; + std::string content_type; + decode_headers(decoding_buffer, headers, content_type); + request.header() = headers; + OPTIONAL body; + body.set_to_omit(); + if (decode_body(decoding_buffer, body, content_type) == -1) { + request.body().set_to_omit(); + } else { + request.body() = body; + } + msg.request() = request; + } + + loggers::get_instance().log_msg("<<< http_codec::decode: ", (const Base_Type &)msg); + return 0; + } catch (const std::logic_error &e) { + return -1; + } +} + +int http_codec::encode_request(const LibItsHttp__TypesAndValues::Request &p_request, TTCN_Buffer &p_encoding_buffer) { + loggers::get_instance().log_msg(">>> http_codec::encode_request: ", (const Base_Type &)p_request); + + // Encode generic part + p_encoding_buffer.put_cs(p_request.method()); + p_encoding_buffer.put_c(' '); + p_encoding_buffer.put_cs(p_request.uri()); + p_encoding_buffer.put_cs(" HTTP/"); + p_encoding_buffer.put_cs(int2str(p_request.version__major())); + p_encoding_buffer.put_c('.'); + p_encoding_buffer.put_cs(int2str(p_request.version__minor())); + p_encoding_buffer.put_cs("\r\n"); + + // Encode headers excepeted the Content-Length + const LibItsHttp__TypesAndValues::Headers &headers = p_request.header(); + std::string content_type; + for (int i = 0; i < headers.size_of(); i++) { + const LibItsHttp__TypesAndValues::Header &header = headers[i]; + loggers::get_instance().log_msg("http_codec::encode_request: Processing header ", header.header__name()); + if (std::string(static_cast(header.header__name())).compare("Content-Length") == 0) { // Skip it, processed later + loggers::get_instance().log("http_codec::encode_request: Skip it"); + continue; + } else { + p_encoding_buffer.put_cs(header.header__name()); + p_encoding_buffer.put_cs(": "); + const OPTIONAL &o = header.header__value(); + if (o.ispresent()) { + const LibItsHttp__TypesAndValues::charstring__list &v = dynamic_cast &>(o); + if (v.size_of() > 0) { + loggers::get_instance().log_msg("http_codec::encode_request: Processing value ", v[0]); + if (std::string(static_cast(header.header__name())).compare("Content-Type") == 0) { // Store it for HTTP body payload encoding + loggers::get_instance().log("http_codec::encode_request: Storing Content-Type"); + int j = 0; + while (j < v.size_of()) { + content_type += v[j++]; + } // End of 'while' statement + } + p_encoding_buffer.put_cs(v[0]); + int j = 1; + while (j < v.size_of()) { + p_encoding_buffer.put_cs(", "); + loggers::get_instance().log_msg("http_codec::encode_request: Processing value ", v[j]); + p_encoding_buffer.put_cs(v[j++]); + } // End of 'while' statement + } + } // else, do not include it + } + p_encoding_buffer.put_cs("\r\n"); + } // End of 'for' statement + + // Encode message body + const OPTIONAL &v = p_request.body(); + OCTETSTRING os; + if (v.ispresent()) { + const LibItsHttp__MessageBodyTypes::HttpMessageBody &body = static_cast(*v.get_opt_value()); + loggers::get_instance().log_msg("http_codec::encode_request: body: ", body); + if (encode_body(body, os, content_type) == -1) { + loggers::get_instance().warning("http_codec::encode_request: Failed to encode HTTP body"); + _ec.length = 0; + _ec.is_content_length_present = 0x00; + } else { + _ec.length = os.lengthof(); + _ec.is_content_length_present = 0x01; + } + loggers::get_instance().log("http_codec::encode_request: length=%d", _ec.length); + } else { + loggers::get_instance().log("http_codec::encode_request: HTTP body field not present"); + _ec.length = 0; + _ec.is_content_length_present = 0x00; + } + + // Encode Content-Length header + p_encoding_buffer.put_cs("Content-Length: "); + if (_ec.length != 0) { + loggers::get_instance().log("http_codec::encode_request: Content-Length: %s", + static_cast(int2str(_ec.length + 2 /*Stand for the last CRLF*/))); + p_encoding_buffer.put_cs(static_cast(int2str(_ec.length))); + _ec.is_content_length_present = 0x01; + } else { + p_encoding_buffer.put_cs("0"); + _ec.is_content_length_present = 0x00; + } + loggers::get_instance().log("http_codec::encode_request: Content-Length: %d - %x", _ec.length, _ec.is_content_length_present); + p_encoding_buffer.put_cs("\r\n"); + + // Add message body + p_encoding_buffer.put_cs("\r\n"); + if (_ec.is_content_length_present == 0x01) { + loggers::get_instance().log_msg("http_codec::encode_request: Add body ", os); + p_encoding_buffer.put_os(os); + // p_encoding_buffer.put_cs("\r\n"); + } + + loggers::get_instance().log_to_hexa("<<< http_codec::encode_request: ", p_encoding_buffer); + return 0; +} + +int http_codec::encode_response(const LibItsHttp__TypesAndValues::Response &p_response, TTCN_Buffer &p_encoding_buffer) { + loggers::get_instance().log_msg(">>> http_codec::encode_response: ", (const Base_Type &)p_response); + + // Encode generic part + p_encoding_buffer.put_cs("HTTP/"); + p_encoding_buffer.put_cs(int2str(p_response.version__major())); + p_encoding_buffer.put_c('.'); + p_encoding_buffer.put_cs(int2str(p_response.version__minor())); + p_encoding_buffer.put_cs(" "); + p_encoding_buffer.put_cs(int2str(p_response.statuscode())); + p_encoding_buffer.put_cs(" "); + if (p_response.statustext().lengthof() != 0) { + p_encoding_buffer.put_cs(p_response.statustext()); + } + p_encoding_buffer.put_cs("\r\n"); + + // Encode headers excepeted the Content-Length + const LibItsHttp__TypesAndValues::Headers &headers = p_response.header(); + std::string content_type; + for (int i = 0; i < headers.size_of(); i++) { + const LibItsHttp__TypesAndValues::Header &header = headers[i]; + loggers::get_instance().log_msg("http_codec::encode_response: Processing header ", header.header__name()); + p_encoding_buffer.put_cs(header.header__name()); + p_encoding_buffer.put_cs(": "); + if (std::string(static_cast(header.header__name())).compare("Content-Length") == 0) { + continue; + } else { + const OPTIONAL &o = header.header__value(); + if (o.ispresent()) { + const LibItsHttp__TypesAndValues::charstring__list &v = dynamic_cast &>(o); + if (v.size_of() > 0) { + loggers::get_instance().log_msg("http_codec::encode_response: Processing value ", v[0]); + if (std::string(static_cast(header.header__name())).compare("Content-Type") == 0) { // Store it for HTTP body payload encoding + loggers::get_instance().log("http_codec::encode_response: Storing Content-Type"); + int j = 0; + while (j < v.size_of()) { + content_type += v[j++]; + } // End of 'while' statement + } + p_encoding_buffer.put_cs(v[0]); + int j = 1; + while (j < v.size_of()) { + p_encoding_buffer.put_cs(", "); + loggers::get_instance().log_msg("http_codec::encode_response: Processing value ", v[j]); + p_encoding_buffer.put_cs(v[j++]); + j += 1; + } // End of 'while' statement + } + } // else, do not include it + } + p_encoding_buffer.put_cs("\r\n"); + } // End of 'for' statement + + // Encode message body + const OPTIONAL &v = p_response.body(); + OCTETSTRING os; + if (v.ispresent()) { + const LibItsHttp__MessageBodyTypes::HttpMessageBody &body = static_cast(*v.get_opt_value()); + loggers::get_instance().log_msg("http_codec::encode_response: body: ", body); + if (encode_body(body, os, content_type) == -1) { + _ec.length = 0; + _ec.is_content_length_present = 0x00; + } else { + _ec.length = os.lengthof(); + _ec.is_content_length_present = 0x01; + } + loggers::get_instance().log("http_codec::encode_response: length=%d", _ec.length); + } else { + loggers::get_instance().log("http_codec::encode_response: HTTP body field not present"); + _ec.length = 0; + _ec.is_content_length_present = 0x00; + } + + // Encode Content-Length header + p_encoding_buffer.put_cs("Content-Length: "); + if (_ec.length != 0) { + loggers::get_instance().log("http_codec::encode_request: Content-Length: %s", + static_cast(int2str(_ec.length + 2 /*Stand for the last CRLF*/))); + p_encoding_buffer.put_cs(static_cast(int2str(_ec.length))); + _ec.is_content_length_present = 0x01; + } else { + p_encoding_buffer.put_cs("0"); + _ec.is_content_length_present = 0x00; + } + loggers::get_instance().log("http_codec::encode_request: Content-Length: %d - %x", _ec.length, _ec.is_content_length_present); + p_encoding_buffer.put_cs("\r\n"); + + // Add message body + p_encoding_buffer.put_cs("\r\n"); + if (_ec.is_content_length_present == 0x01) { + loggers::get_instance().log_msg("http_codec::encode_request: Add body ", os); + p_encoding_buffer.put_os(os); + // p_encoding_buffer.put_cs("\r\n"); + } + + loggers::get_instance().log_to_hexa("<<< http_codec::encode_response: ", p_encoding_buffer); + return 0; +} + +int http_codec::decode_headers(TTCN_Buffer &decoding_buffer, LibItsHttp__TypesAndValues::Headers &headers, std::string &p_content_type) { + loggers::get_instance().log(">>> http_codec::decode_headers"); + loggers::get_instance().log_to_hexa("http_codec::decode_headers", decoding_buffer); + + CHARSTRING cstr; + int i = 0; + while (true) { + switch (get_line(decoding_buffer, cstr, true)) { + case 0: { + loggers::get_instance().log_msg("http_codec::decode_headers: ", cstr); + LibItsHttp__TypesAndValues::Header header; + if (decode_header(cstr, header) == -1) { + loggers::get_instance().warning("http_codec::decode_headers: Failed to decode header %s", static_cast(cstr)); + return -1; + } + headers[i++] = header; + if (std::string(static_cast(header.header__name())).compare("Content-Type") == 0) { + if (header.header__value().is_present() != 0) { + const PreGenRecordOf::PREGEN__RECORD__OF__CHARSTRING &l = + static_cast(*header.header__value().get_opt_value()); + p_content_type = static_cast(l[0]); + } else { + p_content_type = ""; + } + } + } break; + case 1: + loggers::get_instance().log_msg("<<< http_codec::decode_headers: ", headers); + return 0; + case -1: + loggers::get_instance().warning("http_codec::decode_headers: Failed to decode headers"); + return -1; + } // End of 'switch' statement + } // End of 'while' statement +} + +int http_codec::decode_header(CHARSTRING &header_line, LibItsHttp__TypesAndValues::Header &header) { + loggers::get_instance().log_msg(">>> http_codec::decode_header", header_line); + + try { + std::string str(static_cast(header_line)); + std::regex rgx("([0-9a-zA-Z-]+)\\:\\s+(.+)(,(.+))*"); + std::sregex_iterator begin(str.cbegin(), str.cend(), rgx); + std::smatch m = *begin; + if (m.size() < 5) { + loggers::get_instance().warning("http_codec::decode_header: Failed to decode header %s", str.c_str()); + return -1; + } + loggers::get_instance().log("http_codec::decode_header: %d", m.size()); + header.header__name() = CHARSTRING(m[1].str().c_str()); + LibItsHttp__TypesAndValues::charstring__list v; + for (unsigned int j = 0; j < m.size(); j++) { + if (m[j + 2].str().length() == 0) { + break; + } + v[j] = CHARSTRING(m[j + 2].str().c_str()); + } // End of 'for' statement + header.header__value() = OPTIONAL(v); + + if (m[1].str().compare("Content-Length") == 0) { + // Save the the body length + loggers::get_instance().log("http_codec::decode_header: decoded Content-Length %s", m[2].str().c_str()); + _dc.length = std::stoi(m[2].str()); + } else if (m[1].str().compare("Transfer-Encoding") == 0) { + if (m[2].str().find("chunked") != std::string::npos) { + _dc.chunked = true; + loggers::get_instance().log("http_codec::decode_header: decoded Transfer-Encoding %x", _dc.chunked); + } + } + + return 0; + } catch (const std::logic_error &e) { + return -1; + } +} + +int http_codec::encode_body(const LibItsHttp__MessageBodyTypes::HttpMessageBody &p_message_body, OCTETSTRING &p_encoding_buffer, + const std::string &p_content_type) { + loggers::get_instance().log_msg(">>> http_codec::encode_body: ", (const Base_Type &)p_message_body); + + // Sanity check + if (p_content_type.empty()) { + loggers::get_instance().warning("http_codec::encode_body: Failed to select a codec for HTTP body payload"); + return -1; + } + + if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_binary__body)) { + const LibItsHttp__BinaryMessageBodyTypes::BinaryBody &binary_body = p_message_body.binary__body(); + if (binary_body.ischosen(LibItsHttp__BinaryMessageBodyTypes::BinaryBody::ALT_raw)) { + p_encoding_buffer = OCTETSTRING(binary_body.raw().lengthof(), (unsigned char *)static_cast(binary_body.raw())); + } else { + std::map>>::const_iterator it; + bool processed = false; + if (p_content_type.find("x-its") != std::string::npos) { + loggers::get_instance().log("http_codec::encode_body: Find x-its"); + it = _codecs.find("http_its"); // TODO Use params + if (it != _codecs.cend()) { + 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 + processed = true; + } + } // TODO Add new HTTP message codec here + if (!processed) { + loggers::get_instance().warning("http_codec::encode_body: Unsupported HTTP codec, use raw field as default"); + p_encoding_buffer = OCTETSTRING(0, nullptr); + } + } + } else if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_html__body)) { + p_encoding_buffer = OCTETSTRING(p_message_body.html__body().lengthof(), (unsigned char *)static_cast(p_message_body.html__body())); + } else if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_text__body)) { + p_encoding_buffer = OCTETSTRING(p_message_body.text__body().lengthof(), (unsigned char *)static_cast(p_message_body.text__body())); + } else if (p_message_body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_xml__body)) { + const LibItsHttp__XmlMessageBodyTypes::XmlBody &xml_body = p_message_body.xml__body(); + if (xml_body.ischosen(LibItsHttp__XmlMessageBodyTypes::XmlBody::ALT_raw)) { + p_encoding_buffer = OCTETSTRING(xml_body.raw().lengthof(), (unsigned char *)static_cast(xml_body.raw())); + } else { + std::map>>::const_iterator it; + bool processed = false; + loggers::get_instance().log("http_codec::encode_body: Content-Type:'%s'", p_content_type.c_str()); + if (p_content_type.find("held") != std::string::npos) { + it = _codecs.find("held"); // TODO Use params + if (it != _codecs.cend()) { + loggers::get_instance().log("http_codec::encode_body: Call 'held_codec'"); + _codecs["held"]->encode((Record_Type &)xml_body, p_encoding_buffer); // TODO Use params + processed = true; + } + } else if (p_content_type.find("lost") != std::string::npos) { + it = _codecs.find("lost"); // TODO Use params + if (it != _codecs.cend()) { + loggers::get_instance().log("http_codec::encode_body: Call 'lost_codec'"); + _codecs["lost"]->encode((Record_Type &)xml_body, p_encoding_buffer); // TODO Use params + processed = true; + } + } // TODO Add new HTTP message codec here + if (!processed) { + loggers::get_instance().warning("http_codec::encode_body: Unsupported HTTP codec, use raw field as default"); + p_encoding_buffer = OCTETSTRING(0, nullptr); + } + } + } else { + loggers::get_instance().warning("http_codec::encode_body: Failed to encode HTTP message body"); + return -1; + } + loggers::get_instance().log_msg("http_codec::encode_body: HTTP message ", p_encoding_buffer); + _ec.length = p_encoding_buffer.lengthof(); + loggers::get_instance().log("http_codec::encode_body: HTTP message length: %d", _ec.length); + + return 0; +} + +int http_codec::decode_body(TTCN_Buffer &decoding_buffer, LibItsHttp__MessageBodyTypes::HttpMessageBody &message_body, const std::string &p_content_type) { + loggers::get_instance().log(">>> http_codec::decode_body"); + loggers::get_instance().log_to_hexa("http_codec::decode_body", decoding_buffer); + loggers::get_instance().log("http_codec::decode_body: # of codecs=%d - %p", _codecs.size(), this); + loggers::get_instance().log("http_codec::decode_body: Content-Type=%s", p_content_type.c_str()); + + // Sanity checks + if (decoding_buffer.get_len() - decoding_buffer.get_pos() <= 0) { + return -1; + } + /* TODO Uncommentif (p_content_type.empty()) { + loggers::get_instance().warning("http_codec::encode_body: Failed to select a codec for HTTP body payload"); + return -1; + }*/ + + 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); + + // 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; + if (_dc.length != 0) { + const unsigned char *p = static_cast(s); + if ((unsigned int)s.lengthof() <= _dc.length) { + body = OCTETSTRING(s.lengthof(), p); + } else { + body = OCTETSTRING(_dc.length, p); + } + } else { + loggers::get_instance().warning("http_codec::decode_body: No Conten-Length header, process all remaining bytes"); + body = s; + } + loggers::get_instance().log_msg("http_codec::decode_body: Aligned body=", body); + loggers::get_instance().log("http_codec::decode_body: body length=%d", body.lengthof()); + /* TODO To be removed + // Remove CRLF if any + int counter = 0; + if ((body[body.lengthof() - 1].get_octet() == 0x0d) || (body[body.lengthof() - 1].get_octet() == 0x0a)) { + counter += 1; + if ((body[body.lengthof() - 2].get_octet() == 0x0d) || (body[body.lengthof() - 2].get_octet() == 0x0a)) { + counter += 1; + } + } + loggers::get_instance().log("http_codec::decode_body: counter=%d", counter); + body = OCTETSTRING(body.lengthof() - counter, static_cast(body)); + */ + if (_dc.chunked) { + int counter = 0; + int prev = 0; + OCTETSTRING os(0, nullptr); + do { + while (counter < body.lengthof()) { // Extract the size of the chunk \r[\n] + if ((body[counter].get_octet() == '\r') || (body[counter].get_octet() == '\n')) { + break; + } + counter += 1; + } // End of 'while' statement + loggers::get_instance().log("http_codec::decode_body: Chunked(0): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); + if (counter < body.lengthof()) { + int idx = counter - prev; + OCTETSTRING trunk(idx, static_cast(body)); + loggers::get_instance().log_msg("http_codec::decode_body: trunk: ", trunk); + std::string str((const char *)static_cast(trunk), idx); + loggers::get_instance().log("http_codec::decode_body: str: '%s'", str.c_str()); + int len = std::stoi(str, nullptr, 16); // converter::get_instance().string_to_int(str); + loggers::get_instance().log("http_codec::decode_body: Chunk len: %d", len); + while (counter < body.lengthof() && ((body[counter].get_octet() == '\r') || (body[counter].get_octet() == '\n'))) { // Skip additional \n + counter += 1; + } // End of 'while' statement + if (counter < body.lengthof()) { + loggers::get_instance().log("http_codec::decode_body: Chunked (1): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); + os += OCTETSTRING(len, counter + static_cast(body)); + loggers::get_instance().log_msg("http_codec::decode_body: os=", os); + counter += len; + loggers::get_instance().log("http_codec::decode_body: Chunked: %02x %02x %02x", body[counter].get_octet(), body[counter + 1].get_octet(), + body[counter + 2].get_octet()); + loggers::get_instance().log("http_codec::decode_body: Chunked (2): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); + while (counter < body.lengthof() && ((body[counter].get_octet() == '\r') || (body[counter].get_octet() == '\n'))) { // Skip additional \n + counter += 1; + } // End of 'while' statement + prev = counter; + loggers::get_instance().log("http_codec::decode_body: Chunked (3): prev = %d, counter=%d / %d", prev, counter, body.lengthof()); + } + } + } while (counter < body.lengthof()); // Process next chunk if any + body = os; + loggers::get_instance().log_msg("http_codec::decode_body: Finalised body=", body); + } + // Check if HTTP message body contains binary characters + for (int i = 0; i < body.lengthof(); i++) { + unsigned char c = body[i].get_octet(); + if (!std::isprint(c) && !std::isspace(c) && !std::ispunct(c)) { + loggers::get_instance().log("http_codec::decode_body: Byte #%d is not printable: 0x%02x", i, body[i].get_octet()); + _dc.is_binary = 0x01; + break; + } + } // End of 'for' statement + loggers::get_instance().log("http_codec::decode_body: Binary mode: %x", _dc.is_binary); + LibItsHttp__MessageBodyTypes::HttpMessageBody v; + if (_dc.is_binary == 0x01) { + LibItsHttp__BinaryMessageBodyTypes::BinaryBody binary_body; + std::map>>::const_iterator it; + bool processed = false; + // TODO To be refined adding a string identifier to check which codec to use. E.g. held_code.id() returns "xmlns=\"urn:ietf:params:xml:ns:geopriv:held\">" + if (p_content_type.find("x-its") != std::string::npos) { + loggers::get_instance().log("http_codec::decode_body: Find 'x-its'"); + it = _codecs.cbegin(); //_codecs.find("http_its"); + if (it != _codecs.cend()) { + /*** + FIXME: + This code generate a codedump, I don't undertsand the reason. + The same code works file for Ng112 HELD & LOST codec. Ununderstandable!!!! + ==> Use a patch + if (_codecs["http_its"].get() != nullptr) { + loggers::get_instance().log("http_codec::decode_body: Call 'http_etsi_ieee1609dot2_codec'"); + if (_codecs["http_its"]->decode(body, (Record_Type&)binary_body) == 0) { + processed = true; + } + }*/ + loggers::get_instance().log("http_codec::decode_body: Call '%s'", it->first.c_str()); + http_etsi_ieee1609dot2_codec *codec = new http_etsi_ieee1609dot2_codec(); + if (codec->decode(body, binary_body.ieee1609dot2__data()) == 0) { + message_body.binary__body() = binary_body; + processed = true; + } + delete codec; + } + } // TODO Add new HTTP message codec here + if (!processed) { + loggers::get_instance().warning("http_codec::decode_body: Unsupported HTTP codec, use raw field as default"); + binary_body.raw() = body; + message_body.binary__body() = binary_body; + } + } else { + // Convert into string + params p; + p["decode_str"] = std::string(static_cast(body), body.lengthof() + static_cast(body)); + loggers::get_instance().log("http_codec::decode_body: decode_str: %s", p["decode_str"].c_str()); + // Try to identify xml + if (p["decode_str"].find("" + if ((p["decode_str"].find("=\"urn:ietf:params:xml:ns:geopriv:held\"") != std::string::npos) || + (p["decode_str"].find("=\"urn:ietf:params:xml:ns:pidf\"") != std::string::npos)) { + loggers::get_instance().log("http_codec::decode_body: Find 'urn:ietf:params:xml:ns:geopriv:held'"); + if (_codecs["held"].get() != nullptr) { + loggers::get_instance().log("http_codec::decode_body: Call 'held_codec'"); + if (_codecs["held"]->decode(body, (Record_Type &)xml_body, &p) == -1) { + loggers::get_instance().warning("http_codec::decode_body: Failed to decode HELD message"); + xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + } else { + loggers::get_instance().log_msg("http_codec::decode_body: Decoded message:", xml_body); + message_body.xml__body() = xml_body; + } + } else { + loggers::get_instance().warning("http_codec::decode_body: No codec for HELD"); + xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + } + message_body.xml__body() = xml_body; + } else if (p["decode_str"].find("=\"urn:ietf:params:xml:ns:lost1\"") != std::string::npos) { + loggers::get_instance().log("http_codec::decode_body: Find 'urn:ietf:params:xml:ns:lost1'"); + if (_codecs["lost"].get() != nullptr) { + loggers::get_instance().log("http_codec::decode_body: Call 'lost_codec'"); + if (_codecs["lost"]->decode(body, (Record_Type &)xml_body, &p) == -1) { + loggers::get_instance().warning("http_codec::decode_body: Failed to decode LOST message"); + xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + } else { + loggers::get_instance().log_msg("http_codec::decode_body: Decoded message:", xml_body); + message_body.xml__body() = xml_body; + } + } else { + loggers::get_instance().warning("http_codec::decode_body: No codec for LOST"); + xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + } + message_body.xml__body() = xml_body; + } else { + loggers::get_instance().warning("http_codec::decode_body: No XML codec found"); + xml_body.raw() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + message_body.xml__body() = xml_body; + } + } else if (p["decode_str"].find("") != std::string::npos) { // Try to identify HTML + loggers::get_instance().log("http_codec::decode_body: Find html message"); + LibItsHttp__MessageBodyTypes::HtmlBody html_body; + message_body.html__body() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + } else { + loggers::get_instance().log("http_codec::decode_body: Use textBdy as default"); + LibItsHttp__MessageBodyTypes::TextBody text_body; + message_body.text__body() = CHARSTRING(body.lengthof(), (char *)static_cast(body)); + } + } + + return 0; +} + +int http_codec::get_line(TTCN_Buffer &buffer, CHARSTRING &to, const bool concatenate_header_lines) { + unsigned int i = 0; + const unsigned char *cc_to = buffer.get_read_data(); + + // Sanity checks + if (buffer.get_read_len() == 0) { + return -1; + } + + while (true) { + // Skip spaces, and empty lines + for (; i < buffer.get_read_len() && cc_to[i] != '\0' && cc_to[i] != '\r' && cc_to[i] != '\n'; i++) + ; + if (i >= buffer.get_read_len()) { // No more characters to process + to = CHARSTRING(""); + return -1; + } else if (cc_to[i] == '\n') { // New line found, we don't care is '\r' is missing + if ((i > 0) && ((i + 1) < buffer.get_read_len()) && concatenate_header_lines && ((cc_to[i + 1] == ' ') || (cc_to[i + 1] == '\t'))) { + i += 1; // Skip it + } else { + to = CHARSTRING(i, (const char *)cc_to); + buffer.set_pos(buffer.get_pos() + i + 1); + return i == 0 ? 1 : 0; + } + } else { + if ((i + 1) < buffer.get_read_len() && cc_to[i + 1] != '\n') { + return -1; + } else if (i > 0 && (i + 2) < buffer.get_read_len() && concatenate_header_lines && (cc_to[i + 2] == ' ' || cc_to[i + 2] == '\t')) { + i += 2; + } else { + to = CHARSTRING(i, (const char *)cc_to); + buffer.set_pos(buffer.get_pos() + i + 2); + return i == 0 ? 1 : 0; + } + } + } // End of 'while' statement +} + +void http_codec::set_payload_codecs(const std::string &p_codecs) { + loggers::get_instance().log(">>> http_codec::set_payload_codecs: %s", p_codecs.c_str()); + + // Sanity check + if (p_codecs.length() == 0) { + return; + } + + // Extract codecs + try { + std::regex rgx("(\\w+):(\\w+)(;(\\w+):(\\w+))*"); + std::sregex_iterator begin(p_codecs.cbegin(), p_codecs.cend(), rgx); + std::sregex_iterator end = std::sregex_iterator(); + // E.g. 9 - xml - :held_codec - held_codec - ;html:html_codec - html:html_codec - html - :html_codec - html_codec + for (std::sregex_iterator it = begin; it != end; ++it) { + std::smatch m = *it; + loggers::get_instance().log("http_codec::set_payload_codecs: %d - %s - %s - %s - %s - %s - %s - %s - %s", m.size(), m[1].str().c_str(), + m[2].str().c_str(), m[3].str().c_str(), m[4].str().c_str(), m[5].str().c_str(), m[6].str().c_str(), m[7].str().c_str(), + m[8].str().c_str()); + for (unsigned int j = 1; j < m.size() - 1; j += 3) { // Exclude m[0] + loggers::get_instance().log("http_codec::set_payload_codecs: insert (%s, %s), j = %d", m[j].str().c_str(), m[j + 1].str().c_str(), j); + if (m[j].str().empty()) { + break; + } + std::string key(m[j].str()); + loggers::get_instance().log("http_codec::set_payload_codecs: Add codec %s", key.c_str()); + _codecs.insert( + std::make_pair(key, std::unique_ptr>(codec_stack_builder::get_instance()->get_codec(m[j + 1].str().c_str())))); + } // End of 'for' statement + } // End of 'for' statement + loggers::get_instance().log("http_codec::set_payload_codecs: _codecs length=%d - %p", _codecs.size(), this); + } catch (const std::logic_error &e) { + loggers::get_instance().warning("http_codec::set_payload_codecs: std::logic_error: %s", e.what()); + _codecs.clear(); + } +} diff --git a/ccsrc/Protocols/Http/http_codec.hh b/ccsrc/Protocols/Http/http_codec.hh index a06f6a8f1830a3168fb8325ce3bdf6e30139db54..91c799e530eb6fbc43202955df61dd2c62b138fb 100644 --- a/ccsrc/Protocols/Http/http_codec.hh +++ b/ccsrc/Protocols/Http/http_codec.hh @@ -1,72 +1,72 @@ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsHttp__TypesAndValues { - class HttpMessage; - class Request; - class Response; - class Headers; - class Header; -} // namespace LibItsHttp__TypesAndValues -namespace LibItsHttp__MessageBodyTypes { - class HttpMessageBody; -} - -struct encoding_context { - unsigned int length; - unsigned char is_content_length_present; - - encoding_context() { reset(); }; - void reset() { - length = -1; - is_content_length_present = 0x00; - }; -}; - -struct decoding_context { - unsigned int length; - unsigned char is_binary; - bool chunked; - - decoding_context() { reset(); }; - void reset() { - length = -1; - is_binary = 0x00; - chunked = false; - }; -}; - -class http_codec : public codec { - encoding_context _ec; - decoding_context _dc; - std::map>> _codecs; - -public: - explicit http_codec() : codec(), _ec(), _dc(), _codecs(){}; - virtual ~http_codec(){}; - - virtual int encode(const LibItsHttp__TypesAndValues::HttpMessage &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, LibItsHttp__TypesAndValues::HttpMessage &, params *params = NULL); - - void set_payload_codecs(const std::string &p_codecs); - -private: - int encode_request(const LibItsHttp__TypesAndValues::Request &p_request, TTCN_Buffer &p_encoding_buffer); - int encode_response(const LibItsHttp__TypesAndValues::Response &p_response, TTCN_Buffer &p_encoding_buffer); - int encode_body(const LibItsHttp__MessageBodyTypes::HttpMessageBody &p_message_body, OCTETSTRING &p_encoding_buffer, const std::string &p_content_type); - - int decode_headers(TTCN_Buffer &decoding_buffer, LibItsHttp__TypesAndValues::Headers &headers, std::string &p_content_type); - int decode_header(CHARSTRING &header_line, LibItsHttp__TypesAndValues::Header &header); - int decode_body(TTCN_Buffer &decoding_buffer, LibItsHttp__MessageBodyTypes::HttpMessageBody &message_body, const std::string &p_content_type); - int get_line(TTCN_Buffer &buffer, CHARSTRING &to, const bool concatenate_header_lines = false); - -}; // End of class http_codec +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsHttp__TypesAndValues { + class HttpMessage; + class Request; + class Response; + class Headers; + class Header; +} // namespace LibItsHttp__TypesAndValues +namespace LibItsHttp__MessageBodyTypes { + class HttpMessageBody; +} + +struct encoding_context { + unsigned int length; + unsigned char is_content_length_present; + + encoding_context() { reset(); }; + void reset() { + length = -1; + is_content_length_present = 0x00; + }; +}; + +struct decoding_context { + unsigned int length; + unsigned char is_binary; + bool chunked; + + decoding_context() { reset(); }; + void reset() { + length = -1; + is_binary = 0x00; + chunked = false; + }; +}; + +class http_codec : public codec { + encoding_context _ec; + decoding_context _dc; + std::map>> _codecs; + +public: + explicit http_codec() : codec(), _ec(), _dc(), _codecs(){}; + virtual ~http_codec(){}; + + virtual int encode(const LibItsHttp__TypesAndValues::HttpMessage &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, LibItsHttp__TypesAndValues::HttpMessage &, params *params = NULL); + + void set_payload_codecs(const std::string &p_codecs); + +private: + int encode_request(const LibItsHttp__TypesAndValues::Request &p_request, TTCN_Buffer &p_encoding_buffer); + int encode_response(const LibItsHttp__TypesAndValues::Response &p_response, TTCN_Buffer &p_encoding_buffer); + int encode_body(const LibItsHttp__MessageBodyTypes::HttpMessageBody &p_message_body, OCTETSTRING &p_encoding_buffer, const std::string &p_content_type); + + int decode_headers(TTCN_Buffer &decoding_buffer, LibItsHttp__TypesAndValues::Headers &headers, std::string &p_content_type); + int decode_header(CHARSTRING &header_line, LibItsHttp__TypesAndValues::Header &header); + int decode_body(TTCN_Buffer &decoding_buffer, LibItsHttp__MessageBodyTypes::HttpMessageBody &message_body, const std::string &p_content_type); + int get_line(TTCN_Buffer &buffer, CHARSTRING &to, const bool concatenate_header_lines = false); + +}; // End of class http_codec diff --git a/ccsrc/Protocols/Http/http_layer.cc b/ccsrc/Protocols/Http/http_layer.cc index de29bc7b5f1f60f85f448a5b77b8c04af9d9d502..227e5c0a37697c1e3dcb806c54e1932c526a2c13 100644 --- a/ccsrc/Protocols/Http/http_layer.cc +++ b/ccsrc/Protocols/Http/http_layer.cc @@ -1,128 +1,128 @@ -#include "LibItsHttp_TypesAndValues.hh" - -#include "codec_stack_builder.hh" -#include "http_layer_factory.hh" - -#include "loggers.hh" - -#include "converter.hh" - -using namespace std; // Required for isnan() -#include "LibItsHttp_TestSystem.hh" -#include "LibItsHttp_TypesAndValues.hh" - -http_layer::http_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _device_mode{false} { - loggers::get_instance().log(">>> http_layer::http_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - - params::const_iterator it = _params.find(params::codecs); - if (it != _params.cend()) { - _codec.set_payload_codecs(it->second); - } - it = _params.find(params::device_mode); - if (it != _params.cend()) { - _device_mode = (1 == converter::get_instance().string_to_int(it->second)); - } - it = _params.find(params::method); - if (it == _params.cend()) { - _params[params::method] = "POST"; - } - it = _params.find(params::uri); - if (it == _params.cend()) { - _params[params::uri] = "/"; - } - it = _params.find(params::host); - if (it == _params.cend()) { - _params[params::host] = "127.0.0.1"; - } - it = _params.find(params::content_type); - if (it == _params.cend()) { - _params[params::content_type] = "application/text"; - } -} - -void http_layer::sendMsg(const LibItsHttp__TypesAndValues::HttpMessage &p_http_message, params &p_param) { - loggers::get_instance().log_msg(">>> http_layer::sendMsg: ", p_http_message); - - // Encode HttpMessage - OCTETSTRING data; - _codec.encode(p_http_message, data); - send_data(data, _params); -} - -void http_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> http_layer::send_data: ", data); - - if (_device_mode) { // Need to build an HTTP packet - loggers::get_instance().log("http_layer::send_data: Build http layer"); - TTCN_Buffer buffer; - buffer.put_cs(_params[params::method].c_str()); - buffer.put_c(' '); - buffer.put_cs(_params[params::uri].c_str()); - buffer.put_cs(" HTTP/1.1\r\n"); - buffer.put_cs("Host: "); - buffer.put_cs(_params[params::host].c_str()); - buffer.put_cs("\r\n"); - buffer.put_cs("Content-type: "); - buffer.put_cs(_params[params::content_type].c_str()); - buffer.put_cs("\r\n"); - buffer.put_cs("Content-length: "); - buffer.put_cs(static_cast(int2str(data.lengthof() + 2 /*Stand for the last CRLF*/))); - buffer.put_cs("\r\n\r\n"); - buffer.put_os(data); - buffer.put_cs("\r\n"); - data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - } - - loggers::get_instance().log_msg("http_layer::send_data: ", data); - send_to_all_layers(data, params); -} - -void http_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> http_layer::receive_data: ", data); - - // Decode HTTP message - LibItsHttp__TypesAndValues::HttpMessage http_message; - if (_codec.decode(data, http_message) == -1) { - loggers::get_instance().warning("http_layer::receive_data: Failed to decode data"); - return; - } - if (_device_mode) { - OCTETSTRING os; - if (http_message.ischosen(LibItsHttp__TypesAndValues::HttpMessage::ALT_response)) { - if (http_message.response().body().ispresent()) { - LibItsHttp__MessageBodyTypes::HttpMessageBody &body = - static_cast(*http_message.response().body().get_opt_value()); - if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_binary__body)) { - LibItsHttp__BinaryMessageBodyTypes::BinaryBody &binary = body.binary__body(); - if (binary.ischosen(LibItsHttp__BinaryMessageBodyTypes::BinaryBody::ALT_raw)) { - os = binary.raw(); - } else { - loggers::get_instance().warning("http_layer::receive_data: A raw binary payload is expected"); - } - } else if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_html__body)) { - // TODO To be done - loggers::get_instance().warning("http_layer::receive_data: Not implemented yet"); - } else if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_xml__body)) { - // TODO To be done - loggers::get_instance().warning("http_layer::receive_data: Not implemented yet"); - } else if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_text__body)) { - // TODO To be done - loggers::get_instance().warning("http_layer::receive_data: Not implemented yet"); - } - receive_to_all_layers(os, params); - } else { - loggers::get_instance().warning("http_layer::receive_data: No body present"); - } - } else { - loggers::get_instance().warning("http_layer::receive_data: An HTTP response is expected"); - } - } else { - // Pass it to the ports - to_all_upper_ports(http_message, params); - } -} - -http_layer_factory http_layer_factory::_f; +#include "LibItsHttp_TypesAndValues.hh" + +#include "codec_stack_builder.hh" +#include "http_layer_factory.hh" + +#include "loggers.hh" + +#include "converter.hh" + +using namespace std; // Required for isnan() +#include "LibItsHttp_TestSystem.hh" +#include "LibItsHttp_TypesAndValues.hh" + +http_layer::http_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _device_mode{false} { + loggers::get_instance().log(">>> http_layer::http_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + + params::const_iterator it = _params.find(params::codecs); + if (it != _params.cend()) { + _codec.set_payload_codecs(it->second); + } + it = _params.find(params::device_mode); + if (it != _params.cend()) { + _device_mode = (1 == converter::get_instance().string_to_int(it->second)); + } + it = _params.find(params::method); + if (it == _params.cend()) { + _params[params::method] = "POST"; + } + it = _params.find(params::uri); + if (it == _params.cend()) { + _params[params::uri] = "/"; + } + it = _params.find(params::host); + if (it == _params.cend()) { + _params[params::host] = "127.0.0.1"; + } + it = _params.find(params::content_type); + if (it == _params.cend()) { + _params[params::content_type] = "application/text"; + } +} + +void http_layer::sendMsg(const LibItsHttp__TypesAndValues::HttpMessage &p_http_message, params &p_param) { + loggers::get_instance().log_msg(">>> http_layer::sendMsg: ", p_http_message); + + // Encode HttpMessage + OCTETSTRING data; + _codec.encode(p_http_message, data); + send_data(data, _params); +} + +void http_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> http_layer::send_data: ", data); + + if (_device_mode) { // Need to build an HTTP packet + loggers::get_instance().log("http_layer::send_data: Build http layer"); + TTCN_Buffer buffer; + buffer.put_cs(_params[params::method].c_str()); + buffer.put_c(' '); + buffer.put_cs(_params[params::uri].c_str()); + buffer.put_cs(" HTTP/1.1\r\n"); + buffer.put_cs("Host: "); + buffer.put_cs(_params[params::host].c_str()); + buffer.put_cs("\r\n"); + buffer.put_cs("Content-type: "); + buffer.put_cs(_params[params::content_type].c_str()); + buffer.put_cs("\r\n"); + buffer.put_cs("Content-length: "); + buffer.put_cs(static_cast(int2str(data.lengthof() + 2 /*Stand for the last CRLF*/))); + buffer.put_cs("\r\n\r\n"); + buffer.put_os(data); + buffer.put_cs("\r\n"); + data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + } + + loggers::get_instance().log_msg("http_layer::send_data: ", data); + send_to_all_layers(data, params); +} + +void http_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> http_layer::receive_data: ", data); + + // Decode HTTP message + LibItsHttp__TypesAndValues::HttpMessage http_message; + if (_codec.decode(data, http_message) == -1) { + loggers::get_instance().warning("http_layer::receive_data: Failed to decode data"); + return; + } + if (_device_mode) { + OCTETSTRING os; + if (http_message.ischosen(LibItsHttp__TypesAndValues::HttpMessage::ALT_response)) { + if (http_message.response().body().ispresent()) { + LibItsHttp__MessageBodyTypes::HttpMessageBody &body = + static_cast(*http_message.response().body().get_opt_value()); + if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_binary__body)) { + LibItsHttp__BinaryMessageBodyTypes::BinaryBody &binary = body.binary__body(); + if (binary.ischosen(LibItsHttp__BinaryMessageBodyTypes::BinaryBody::ALT_raw)) { + os = binary.raw(); + } else { + loggers::get_instance().warning("http_layer::receive_data: A raw binary payload is expected"); + } + } else if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_html__body)) { + // TODO To be done + loggers::get_instance().warning("http_layer::receive_data: Not implemented yet"); + } else if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_xml__body)) { + // TODO To be done + loggers::get_instance().warning("http_layer::receive_data: Not implemented yet"); + } else if (body.ischosen(LibItsHttp__MessageBodyTypes::HttpMessageBody::ALT_text__body)) { + // TODO To be done + loggers::get_instance().warning("http_layer::receive_data: Not implemented yet"); + } + receive_to_all_layers(os, params); + } else { + loggers::get_instance().warning("http_layer::receive_data: No body present"); + } + } else { + loggers::get_instance().warning("http_layer::receive_data: An HTTP response is expected"); + } + } else { + // Pass it to the ports + to_all_upper_ports(http_message, params); + } +} + +http_layer_factory http_layer_factory::_f; diff --git a/ccsrc/Protocols/Http/http_layer.hh b/ccsrc/Protocols/Http/http_layer.hh index ea55368bc84829274f8a6d7d27316f2e527cd640..5a94e8252d43dfef3821674778157a80fb37052f 100644 --- a/ccsrc/Protocols/Http/http_layer.hh +++ b/ccsrc/Protocols/Http/http_layer.hh @@ -1,83 +1,83 @@ -/*! - * \file http_layer.hh - * \brief Header file for ITS HTTP protocol layer. - * \author ETSI STF549 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "t_layer.hh" - -#include "http_codec.hh" - -namespace LibItsHttp__TestSystem { - class HttpPort; -} - -namespace LibItsHttp__TypesAndValues { - class HttpMessage; //! Forward declaration of TITAN class -} - -class OCTETSTRING; //! Forward declaration of TITAN class - -/*! - * \class http_layer - * \brief This class provides a factory class to create an tcp_layer class instance - */ -class http_layer : public t_layer { - params _params; - http_codec _codec; - bool _device_mode; - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the http_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - http_layer() : t_layer(), _params(), _device_mode{false} { }; - /*! - * \brief Specialised constructor - * Create a new instance of the http_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - http_layer(const std::string& p_type, const std::string& p_param); - /*! - * \brief Default destructor - */ - virtual ~http_layer() { }; - - /*! - * \fn void sendMsg(const LibItsHttp__TypesAndValues::HttpMessage& p_http_message, params& p_param); - * \brief Send HTTP message to the lower layers - * \param[in] p_http_message The GeoNetworking message to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - void sendMsg(const LibItsHttp__TypesAndValues::HttpMessage& p_http_message, params& p_param); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING& data, params& params); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING& data, params& info); -}; // End of class http_layer - +/*! + * \file http_layer.hh + * \brief Header file for ITS HTTP protocol layer. + * \author ETSI STF549 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "t_layer.hh" + +#include "http_codec.hh" + +namespace LibItsHttp__TestSystem { + class HttpPort; +} + +namespace LibItsHttp__TypesAndValues { + class HttpMessage; //! Forward declaration of TITAN class +} + +class OCTETSTRING; //! Forward declaration of TITAN class + +/*! + * \class http_layer + * \brief This class provides a factory class to create an tcp_layer class instance + */ +class http_layer : public t_layer { + params _params; + http_codec _codec; + bool _device_mode; + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the http_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + http_layer() : t_layer(), _params(), _device_mode{false} { }; + /*! + * \brief Specialised constructor + * Create a new instance of the http_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + http_layer(const std::string& p_type, const std::string& p_param); + /*! + * \brief Default destructor + */ + virtual ~http_layer() { }; + + /*! + * \fn void sendMsg(const LibItsHttp__TypesAndValues::HttpMessage& p_http_message, params& p_param); + * \brief Send HTTP message to the lower layers + * \param[in] p_http_message The GeoNetworking message to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + void sendMsg(const LibItsHttp__TypesAndValues::HttpMessage& p_http_message, params& p_param); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING& data, params& params); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING& data, params& info); +}; // End of class http_layer + diff --git a/ccsrc/Protocols/Http/http_layer_factory.hh b/ccsrc/Protocols/Http/http_layer_factory.hh index 55f0e7c14452d8fd60db92272eb53219ff9f64f8..5e4e71abbc84e6265a19065017126e5f6b997a32 100644 --- a/ccsrc/Protocols/Http/http_layer_factory.hh +++ b/ccsrc/Protocols/Http/http_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file http_layer_factory.hh - * \brief Header file for ITS Http protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "http_layer.hh" - -/*! - * \class http_layer_factory - * \brief This class provides a factory class to create an http_layer class instance - */ -class http_layer_factory : public layer_factory { - static http_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the http_layer_factory class - * \remark The HTTP layer identifier is HTTP - */ - http_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("HTTP", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new http_layer(p_type, p_param); }; -}; // End of class http_layer_factory +/*! + * \file http_layer_factory.hh + * \brief Header file for ITS Http protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "http_layer.hh" + +/*! + * \class http_layer_factory + * \brief This class provides a factory class to create an http_layer class instance + */ +class http_layer_factory : public layer_factory { + static http_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the http_layer_factory class + * \remark The HTTP layer identifier is HTTP + */ + http_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("HTTP", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new http_layer(p_type, p_param); }; +}; // End of class http_layer_factory diff --git a/ccsrc/Protocols/Http/module.mk b/ccsrc/Protocols/Http/module.mk index 12304eb0fb337dcd2ae01a6ec3c4c0b0de9483e9..2c92703bd2c872fd65ac098e45ab748fa21018c4 100644 --- a/ccsrc/Protocols/Http/module.mk +++ b/ccsrc/Protocols/Http/module.mk @@ -1,3 +1,3 @@ -sources := http_codec.cc http_layer.cc -includes := . - +sources := http_codec.cc http_layer.cc +includes := . + diff --git a/ccsrc/Protocols/IVIM/ivim_codec.cc b/ccsrc/Protocols/IVIM/ivim_codec.cc index 65ba0e76472497c0ebed14e0f56dd750c072b76d..14c335c21399e0cabd08adc4e6043ed9a5302a34 100644 --- a/ccsrc/Protocols/IVIM/ivim_codec.cc +++ b/ccsrc/Protocols/IVIM/ivim_codec.cc @@ -1,27 +1,27 @@ -#include "ivim_codec.hh" -#include "LibItsIvim_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int ivim_codec::encode(const IVIM__PDU__Descriptions::IVIM &ivim, OCTETSTRING &data) { - loggers::get_instance().log(">>> ivim_codec::encode"); - BITSTRING b; - int rc = asn_codec.encode(ivim, b); - loggers::get_instance().log("ivim_codec::encode: ASN.1 codec returned %d", rc); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("ivim_codec::encode: ", data); - } - return rc; -} - -int ivim_codec::decode(const OCTETSTRING &data, IVIM__PDU__Descriptions::IVIM &ivim, params *params) { - loggers::get_instance().log_msg(">>> ivim_codec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), ivim); - loggers::get_instance().log("ivim_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("ivim_codec::decode: ", ivim); - } - return rc; -} +#include "ivim_codec.hh" +#include "LibItsIvim_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int ivim_codec::encode(const IVIM__PDU__Descriptions::IVIM &ivim, OCTETSTRING &data) { + loggers::get_instance().log(">>> ivim_codec::encode"); + BITSTRING b; + int rc = asn_codec.encode(ivim, b); + loggers::get_instance().log("ivim_codec::encode: ASN.1 codec returned %d", rc); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("ivim_codec::encode: ", data); + } + return rc; +} + +int ivim_codec::decode(const OCTETSTRING &data, IVIM__PDU__Descriptions::IVIM &ivim, params *params) { + loggers::get_instance().log_msg(">>> ivim_codec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), ivim); + loggers::get_instance().log("ivim_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("ivim_codec::decode: ", ivim); + } + return rc; +} diff --git a/ccsrc/Protocols/IVIM/ivim_codec.hh b/ccsrc/Protocols/IVIM/ivim_codec.hh index 47a771241dd263a7ef1a2d515ee0899c40f2954c..b382e5e566751ac8acd323a3f6f84e5cca76390e 100644 --- a/ccsrc/Protocols/IVIM/ivim_codec.hh +++ b/ccsrc/Protocols/IVIM/ivim_codec.hh @@ -1,21 +1,21 @@ -#pragma once - -#include "codec.hh" -#include "ivim_pdu_codec.hh" -#include "params.hh" - -#include "LibItsIvim_TestSystem.hh" -// class BITSTRING; -// class OCTETSTRING; -// class IVIM__PDU__Descriptions::IVIM; - -class ivim_codec : public codec { - ivim_pdu_codec asn_codec; - -public: - explicit ivim_codec() : codec(), asn_codec(){}; - virtual ~ivim_codec(){}; - - virtual int encode(const IVIM__PDU__Descriptions::IVIM &ivim, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, IVIM__PDU__Descriptions::IVIM &, params *params = NULL); -}; // End of class ivim_codec +#pragma once + +#include "codec.hh" +#include "ivim_pdu_codec.hh" +#include "params.hh" + +#include "LibItsIvim_TestSystem.hh" +// class BITSTRING; +// class OCTETSTRING; +// class IVIM__PDU__Descriptions::IVIM; + +class ivim_codec : public codec { + ivim_pdu_codec asn_codec; + +public: + explicit ivim_codec() : codec(), asn_codec(){}; + virtual ~ivim_codec(){}; + + virtual int encode(const IVIM__PDU__Descriptions::IVIM &ivim, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, IVIM__PDU__Descriptions::IVIM &, params *params = NULL); +}; // End of class ivim_codec diff --git a/ccsrc/Protocols/IVIM/ivim_layer.cc b/ccsrc/Protocols/IVIM/ivim_layer.cc index e4d0a4dc0b0cce37951a1ea3d9f27c171dd3a152..1a5e4b1f71f77fc58f424ebf62dcccbc5ebd6e3e 100644 --- a/ccsrc/Protocols/IVIM/ivim_layer.cc +++ b/ccsrc/Protocols/IVIM/ivim_layer.cc @@ -18,7 +18,7 @@ ivim_layer::ivim_layer(const std::string &p_type, const std::string ¶m) : t_ registration::get_instance().add_item(p_type, this); } -void ivim_layer::sendMsg(const LibItsIvim__TestSystem::IvimReq &p, params ¶ms) { +void ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::IvimReq &p, params ¶ms) { loggers::get_instance().log_msg(">>> ivim_layer::sendMsg: ", p); // Encode IVIM PDU @@ -30,7 +30,7 @@ void ivim_layer::sendMsg(const LibItsIvim__TestSystem::IvimReq &p, params ¶m send_data(data, _params); } -void ivim_layer::sendMsg(const LibItsIvim__TestSystem::IvimInd &p, params ¶ms) { +void ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::IvimInd &p, params ¶ms) { loggers::get_instance().log_msg(">>> ivim_layer::sendMsg: ", p); // Encode IVIM PDU @@ -60,7 +60,7 @@ void ivim_layer::receive_data(OCTETSTRING &data, params ¶ms) { } // Decode the payload - LibItsIvim__TestSystem::IvimInd p; + LibItsIvim__TypesAndValues::IvimInd p; _codec.decode(data, p.msgIn()); if (!p.msgIn().is_bound()) { // Discard it diff --git a/ccsrc/Protocols/IVIM/ivim_layer.hh b/ccsrc/Protocols/IVIM/ivim_layer.hh index 09b8aafb5f24d729c211a62ac03bd21476c0d827..b6aac14e8322e17659f7ef675d1b8ba452214894 100644 --- a/ccsrc/Protocols/IVIM/ivim_layer.hh +++ b/ccsrc/Protocols/IVIM/ivim_layer.hh @@ -28,8 +28,8 @@ public: ivim_layer(const std::string &p_type, const std::string ¶m); virtual ~ivim_layer(){}; - void sendMsg(const LibItsIvim__TestSystem::IvimReq &, params ¶ms); - void sendMsg(const LibItsIvim__TestSystem::IvimInd &, params ¶ms); + void sendMsg(const LibItsIvim__TypesAndValues::IvimReq &, params ¶ms); + void sendMsg(const LibItsIvim__TypesAndValues::IvimInd &, params ¶ms); virtual void send_data(OCTETSTRING &data, params ¶ms); virtual void receive_data(OCTETSTRING &data, params &info); diff --git a/ccsrc/Protocols/IVIM/ivim_layer_factory.hh b/ccsrc/Protocols/IVIM/ivim_layer_factory.hh index cbe24b2cc43e022d086a99a7b86125c66fbbc122..c83ed834871c4ee07aa5fc8c12b4c29c10a4dd1d 100644 --- a/ccsrc/Protocols/IVIM/ivim_layer_factory.hh +++ b/ccsrc/Protocols/IVIM/ivim_layer_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file ivim_layer_factory.hh - * \brief Header file for ITS IVIM protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "ivim_layer.hh" - -class ivim_layer_factory : public layer_factory { - static ivim_layer_factory _f; - -public: - ivim_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("IVIM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new ivim_layer(p_type, p_param); }; -}; // End of class ivim_layer_factory +/*! + * \file ivim_layer_factory.hh + * \brief Header file for ITS IVIM protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "ivim_layer.hh" + +class ivim_layer_factory : public layer_factory { + static ivim_layer_factory _f; + +public: + ivim_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("IVIM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new ivim_layer(p_type, p_param); }; +}; // End of class ivim_layer_factory diff --git a/ccsrc/Protocols/IVIM/ivim_pdu_codec.cc b/ccsrc/Protocols/IVIM/ivim_pdu_codec.cc index b89599d29e50fe79b552af4e8576a083482f5e62..2f7609d1eb00e0923d70e272e7cd932ecf80e053 100644 --- a/ccsrc/Protocols/IVIM/ivim_pdu_codec.cc +++ b/ccsrc/Protocols/IVIM/ivim_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "LibItsIvim_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "ivim_codec.hh" -#include "loggers.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_IVIM; -} - -int ivim_pdu_codec::encode(const IVIM__PDU__Descriptions::IVIM &p_ivim, BITSTRING &p_data) { - return _encode(IVIM__PDU__Descriptions::IVIM_descr_, asn_DEF_IVIM, p_ivim, p_data); -} - -int ivim_pdu_codec::decode(const BITSTRING &p_data, IVIM__PDU__Descriptions::IVIM &p_ivim) { - return _decode(IVIM__PDU__Descriptions::IVIM_descr_, asn_DEF_IVIM, p_data, p_ivim); -} +#include "LibItsIvim_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "ivim_codec.hh" +#include "loggers.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_IVIM; +} + +int ivim_pdu_codec::encode(const IVIM__PDU__Descriptions::IVIM &p_ivim, BITSTRING &p_data) { + return _encode(IVIM__PDU__Descriptions::IVIM_descr_, asn_DEF_IVIM, p_ivim, p_data); +} + +int ivim_pdu_codec::decode(const BITSTRING &p_data, IVIM__PDU__Descriptions::IVIM &p_ivim) { + return _decode(IVIM__PDU__Descriptions::IVIM_descr_, asn_DEF_IVIM, p_data, p_ivim); +} diff --git a/ccsrc/Protocols/IVIM/ivim_pdu_codec.hh b/ccsrc/Protocols/IVIM/ivim_pdu_codec.hh index 91eb4d8bb754de677823b31839d2a9da481a6d0e..fae4fc5974c475e03390f4f34bad178de5754363 100644 --- a/ccsrc/Protocols/IVIM/ivim_pdu_codec.hh +++ b/ccsrc/Protocols/IVIM/ivim_pdu_codec.hh @@ -1,17 +1,17 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -#include "LibItsIvim_TestSystem.hh" -// class BITSTRING; -// class OCTETSTRING; -// class IVIM__PDU__Descriptions::IVIM; - -class ivim_pdu_codec : public per_codec { -public: - explicit ivim_pdu_codec(){}; - virtual int encode(const IVIM__PDU__Descriptions::IVIM &ivim, BITSTRING &data); - virtual int decode(const BITSTRING &data, IVIM__PDU__Descriptions::IVIM &); -}; +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +#include "LibItsIvim_TestSystem.hh" +// class BITSTRING; +// class OCTETSTRING; +// class IVIM__PDU__Descriptions::IVIM; + +class ivim_pdu_codec : public per_codec { +public: + explicit ivim_pdu_codec(){}; + virtual int encode(const IVIM__PDU__Descriptions::IVIM &ivim, BITSTRING &data); + virtual int decode(const BITSTRING &data, IVIM__PDU__Descriptions::IVIM &); +}; diff --git a/ccsrc/Protocols/IVIM/ivim_types.hh b/ccsrc/Protocols/IVIM/ivim_types.hh index 11e15c99c9f2ed567f9d52c04cc2b402d81fe8b6..45880aeea0dfb96f6cabda8facd8376741237c7e 100644 --- a/ccsrc/Protocols/IVIM/ivim_types.hh +++ b/ccsrc/Protocols/IVIM/ivim_types.hh @@ -1,15 +1,15 @@ -/*! - * \file ivim_types.hh - * \brief Header file for TITAN IVIM types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsIvim_TestSystem.hh" -#include "LibItsIvim_TypesAndValues.hh" +/*! + * \file ivim_types.hh + * \brief Header file for TITAN IVIM types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsIvim_TestSystem.hh" +#include "LibItsIvim_TypesAndValues.hh" diff --git a/ccsrc/Protocols/IVIM/module.mk b/ccsrc/Protocols/IVIM/module.mk index 625c70ea20fba44ca73161c4ed957f62c81fc241..f71002d84ef793a701bca075b8f05458fbc07d63 100644 --- a/ccsrc/Protocols/IVIM/module.mk +++ b/ccsrc/Protocols/IVIM/module.mk @@ -1,3 +1,3 @@ -sources := ivim_codec.cc ivim_layer.cc ivim_pdu_codec.cc -includes := . - +sources := ivim_codec.cc ivim_layer.cc ivim_pdu_codec.cc +includes := . + diff --git a/ccsrc/Protocols/MapemSpatem/mapem_codec.cc b/ccsrc/Protocols/MapemSpatem/mapem_codec.cc index ce94e0631cb84fa3a9a597926f1ef79d3be57f12..604b2a4377c259d7af29e7807b0e17c2000831f5 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_codec.cc +++ b/ccsrc/Protocols/MapemSpatem/mapem_codec.cc @@ -1,27 +1,27 @@ -#include "mapem_codec.hh" -#include "LibItsMapemSpatem_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int mapem_codec::encode(const MAPEM__PDU__Descriptions::MAPEM &mapem, OCTETSTRING &data) { - loggers::get_instance().log(">>> mapem_codec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(mapem, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("mapem_codec::encode: ", data); - } - return rc; -} - -int mapem_codec::decode(const OCTETSTRING &data, MAPEM__PDU__Descriptions::MAPEM &mapem, params *params) { - loggers::get_instance().log_msg(">>> mapem_codec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), mapem); - loggers::get_instance().log("mapem_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("mapem_codec::decode: ", mapem); - } - return rc; -} +#include "mapem_codec.hh" +#include "LibItsMapemSpatem_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int mapem_codec::encode(const MAPEM__PDU__Descriptions::MAPEM &mapem, OCTETSTRING &data) { + loggers::get_instance().log(">>> mapem_codec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(mapem, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("mapem_codec::encode: ", data); + } + return rc; +} + +int mapem_codec::decode(const OCTETSTRING &data, MAPEM__PDU__Descriptions::MAPEM &mapem, params *params) { + loggers::get_instance().log_msg(">>> mapem_codec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), mapem); + loggers::get_instance().log("mapem_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("mapem_codec::decode: ", mapem); + } + return rc; +} diff --git a/ccsrc/Protocols/MapemSpatem/mapem_codec.hh b/ccsrc/Protocols/MapemSpatem/mapem_codec.hh index 68a3d997427210c260764f614a185caa20b004f2..ecc069877124ccfa7d83d294c41f77c8b2026b3b 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_codec.hh +++ b/ccsrc/Protocols/MapemSpatem/mapem_codec.hh @@ -1,18 +1,18 @@ -#pragma once - -#include "codec.hh" -#include "mapem_pdu_codec.hh" -#include "params.hh" - -#include "LibItsMapemSpatem_TestSystem.hh" - -class mapem_codec : public codec { - mapem_pdu_codec asn_codec; - -public: - explicit mapem_codec() : codec(), asn_codec(){}; - virtual ~mapem_codec(){}; - - virtual int encode(const MAPEM__PDU__Descriptions::MAPEM &sapem, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, MAPEM__PDU__Descriptions::MAPEM &, params *params = NULL); -}; // End of class mapem_codec +#pragma once + +#include "codec.hh" +#include "mapem_pdu_codec.hh" +#include "params.hh" + +#include "LibItsMapemSpatem_TestSystem.hh" + +class mapem_codec : public codec { + mapem_pdu_codec asn_codec; + +public: + explicit mapem_codec() : codec(), asn_codec(){}; + virtual ~mapem_codec(){}; + + virtual int encode(const MAPEM__PDU__Descriptions::MAPEM &sapem, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, MAPEM__PDU__Descriptions::MAPEM &, params *params = NULL); +}; // End of class mapem_codec diff --git a/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.cc b/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.cc index a703ae35f01cc32b8e3d9147a823801bd40b3024..d45ef54fe703b1b0cc740085333fccf8867a8a82 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.cc +++ b/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "LibItsMapemSpatem_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" -#include "mapem_codec.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_MAPEM; -} - -int mapem_pdu_codec::encode(const MAPEM__PDU__Descriptions::MAPEM &p_mapem, BITSTRING &p_data) { - return _encode(MAPEM__PDU__Descriptions::MAPEM_descr_, asn_DEF_MAPEM, p_mapem, p_data); -} - -int mapem_pdu_codec::decode(const BITSTRING &p_data, MAPEM__PDU__Descriptions::MAPEM &p_mapem) { - return _decode(MAPEM__PDU__Descriptions::MAPEM_descr_, asn_DEF_MAPEM, p_data, p_mapem); -} +#include "LibItsMapemSpatem_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" +#include "mapem_codec.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_MAPEM; +} + +int mapem_pdu_codec::encode(const MAPEM__PDU__Descriptions::MAPEM &p_mapem, BITSTRING &p_data) { + return _encode(MAPEM__PDU__Descriptions::MAPEM_descr_, asn_DEF_MAPEM, p_mapem, p_data); +} + +int mapem_pdu_codec::decode(const BITSTRING &p_data, MAPEM__PDU__Descriptions::MAPEM &p_mapem) { + return _decode(MAPEM__PDU__Descriptions::MAPEM_descr_, asn_DEF_MAPEM, p_data, p_mapem); +} diff --git a/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.hh b/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.hh index b2bb8e7f87ec9bb694395351b6f897eafc59a547..684a7e3f3ae113f88fbebd0297d517065a19d97a 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.hh +++ b/ccsrc/Protocols/MapemSpatem/mapem_pdu_codec.hh @@ -1,14 +1,14 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -#include "LibItsMapemSpatem_TestSystem.hh" - -class mapem_pdu_codec : public per_codec { -public: - explicit mapem_pdu_codec(){}; - virtual int encode(const MAPEM__PDU__Descriptions::MAPEM &sapem, BITSTRING &data); - virtual int decode(const BITSTRING &data, MAPEM__PDU__Descriptions::MAPEM &); -}; // End of class mapem_pdu_codec +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +#include "LibItsMapemSpatem_TestSystem.hh" + +class mapem_pdu_codec : public per_codec { +public: + explicit mapem_pdu_codec(){}; + virtual int encode(const MAPEM__PDU__Descriptions::MAPEM &sapem, BITSTRING &data); + virtual int decode(const BITSTRING &data, MAPEM__PDU__Descriptions::MAPEM &); +}; // End of class mapem_pdu_codec diff --git a/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.cc b/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.cc index 9891ad7956389778763185237dea8bcafcbccc0b..a88e5e1327bc307406bd7b9aeeab187fa3792474 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.cc +++ b/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.cc @@ -19,7 +19,7 @@ mapem_spatem_layer::mapem_spatem_layer(const std::string &p_type, const std::str registration::get_instance().add_item(p_type, this); } -void mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TestSystem::MapemReq &p, params ¶ms) { +void mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TypesAndValues::MapemReq &p, params ¶ms) { loggers::get_instance().log_msg(">>> mapem_spatem_layer::sendMsg: ", p); // Encode mapem PDU @@ -32,7 +32,7 @@ void mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TestSystem::MapemReq & send_data(data, _params); } -void mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TestSystem::SpatemReq &p, params ¶ms) { +void mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TypesAndValues::SpatemReq &p, params ¶ms) { loggers::get_instance().log_msg(">>> mapem_spatem_layer::sendMsg: ", p); // Encode spatem PDU @@ -56,7 +56,7 @@ void mapem_spatem_layer::receive_data(OCTETSTRING &data, params ¶ms) { // Sanity check if (*(static_cast(data) + 1) == 0x05) { // Check that received packet has MAPE message id // Decode the MAPEM payload - LibItsMapemSpatem__TestSystem::MapemInd p; + LibItsMapemSpatem__TypesAndValues::MapemInd p; _mapem_codec.decode(data, p.msgIn()); if (!p.msgIn().is_bound()) { // Discard it @@ -139,7 +139,7 @@ void mapem_spatem_layer::receive_data(OCTETSTRING &data, params ¶ms) { to_all_upper_ports(p, params); } else if (*(static_cast(data) + 1) == 0x04) { // Check that received packet has SPATE message id // Decode the SPATEM payload - LibItsMapemSpatem__TestSystem::SpatemInd p; + LibItsMapemSpatem__TypesAndValues::SpatemInd p; _spatem_codec.decode(data, p.msgIn()); if (!p.msgIn().is_bound()) { // Discard it diff --git a/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.hh b/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.hh index 2a8ddfe36384c482c30865050f12870629f0321a..a666a76a995db4be2d073e2faf767084cd423502 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.hh +++ b/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer.hh @@ -32,8 +32,8 @@ public: mapem_spatem_layer(const std::string &p_type, const std::string ¶m); virtual ~mapem_spatem_layer(){}; - void sendMsg(const LibItsMapemSpatem__TestSystem::MapemReq &, params ¶ms); - void sendMsg(const LibItsMapemSpatem__TestSystem::SpatemReq &, params ¶ms); + void sendMsg(const LibItsMapemSpatem__TypesAndValues::MapemReq &, params ¶ms); + void sendMsg(const LibItsMapemSpatem__TypesAndValues::SpatemReq &, params ¶ms); virtual void send_data(OCTETSTRING &data, params ¶ms); virtual void receive_data(OCTETSTRING &data, params &info); diff --git a/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer_factory.hh b/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer_factory.hh index 906a24319dbdedc463189ac847d06571d48a6c6f..50c672aa386b0ec2c960aa3a8c531159ddb85bcb 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer_factory.hh +++ b/ccsrc/Protocols/MapemSpatem/mapem_spatem_layer_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file mapem_spatem_layer_factory.hh - * \brief Header file for ITS MapemSpatem protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "mapem_spatem_layer.hh" - -class mapem_spatem_layer_factory : public layer_factory { - static mapem_spatem_layer_factory _f; - -public: - mapem_spatem_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("MapemSpatem", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new mapem_spatem_layer(p_type, p_param); }; -}; // End of class mapem_spatem_layer_factory +/*! + * \file mapem_spatem_layer_factory.hh + * \brief Header file for ITS MapemSpatem protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "mapem_spatem_layer.hh" + +class mapem_spatem_layer_factory : public layer_factory { + static mapem_spatem_layer_factory _f; + +public: + mapem_spatem_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("MapemSpatem", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new mapem_spatem_layer(p_type, p_param); }; +}; // End of class mapem_spatem_layer_factory diff --git a/ccsrc/Protocols/MapemSpatem/mapem_spatem_types.hh b/ccsrc/Protocols/MapemSpatem/mapem_spatem_types.hh index 27254cf124f4c6d28985a3ef7da4430deccb56dc..ef27a0ff392cabac2d81448d4ee1c183f71f39b2 100644 --- a/ccsrc/Protocols/MapemSpatem/mapem_spatem_types.hh +++ b/ccsrc/Protocols/MapemSpatem/mapem_spatem_types.hh @@ -1,15 +1,15 @@ -/*! - * \file mapem_spatem_types.hh - * \brief Header file for TITAN MAPEM/SPATEM types. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -using namespace std; // Required for isnan() -#include "LibItsMapemSpatem_TestSystem.hh" -#include "LibItsMapemSpatem_TypesAndValues.hh" +/*! + * \file mapem_spatem_types.hh + * \brief Header file for TITAN MAPEM/SPATEM types. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +using namespace std; // Required for isnan() +#include "LibItsMapemSpatem_TestSystem.hh" +#include "LibItsMapemSpatem_TypesAndValues.hh" diff --git a/ccsrc/Protocols/MapemSpatem/module.mk b/ccsrc/Protocols/MapemSpatem/module.mk index 3efd2de129ce7098210822b6c63c13e4c3097b8d..1673a7517b556a07f93ffe804a73bfd3419acdaa 100644 --- a/ccsrc/Protocols/MapemSpatem/module.mk +++ b/ccsrc/Protocols/MapemSpatem/module.mk @@ -1,3 +1,3 @@ -sources := mapem_codec.cc mapem_pdu_codec.cc mapem_spatem_layer.cc spatem_codec.cc spatem_pdu_codec.cc -includes := . - +sources := mapem_codec.cc mapem_pdu_codec.cc mapem_spatem_layer.cc spatem_codec.cc spatem_pdu_codec.cc +includes := . + diff --git a/ccsrc/Protocols/MapemSpatem/spatem_codec.cc b/ccsrc/Protocols/MapemSpatem/spatem_codec.cc index f593d39c4e021454367a137e1aed787df41ed76e..787efcadd4e30248378348384774880bcf4ce5d6 100644 --- a/ccsrc/Protocols/MapemSpatem/spatem_codec.cc +++ b/ccsrc/Protocols/MapemSpatem/spatem_codec.cc @@ -1,27 +1,27 @@ -#include "spatem_codec.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" -#include "mapem_spatem_types.hh" - -int spatem_codec::encode(const SPATEM__PDU__Descriptions::SPATEM &spatem, OCTETSTRING &data) { - loggers::get_instance().log(">>> spatem_codec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(spatem, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("spatem_codec::encode: ", data); - } - return rc; -} - -int spatem_codec::decode(const OCTETSTRING &data, SPATEM__PDU__Descriptions::SPATEM &spatem, params *params) { - loggers::get_instance().log_msg(">>> spatem_codec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), spatem); - loggers::get_instance().log("spatem_codec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("spatem_codec::decode: ", spatem); - } - return rc; -} +#include "spatem_codec.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" +#include "mapem_spatem_types.hh" + +int spatem_codec::encode(const SPATEM__PDU__Descriptions::SPATEM &spatem, OCTETSTRING &data) { + loggers::get_instance().log(">>> spatem_codec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(spatem, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("spatem_codec::encode: ", data); + } + return rc; +} + +int spatem_codec::decode(const OCTETSTRING &data, SPATEM__PDU__Descriptions::SPATEM &spatem, params *params) { + loggers::get_instance().log_msg(">>> spatem_codec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), spatem); + loggers::get_instance().log("spatem_codec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("spatem_codec::decode: ", spatem); + } + return rc; +} diff --git a/ccsrc/Protocols/MapemSpatem/spatem_codec.hh b/ccsrc/Protocols/MapemSpatem/spatem_codec.hh index c3e637662188b56f27050e6e97090dc287291828..ec18d7b16201ac2bb424053d6f3ce337e24f4ba1 100644 --- a/ccsrc/Protocols/MapemSpatem/spatem_codec.hh +++ b/ccsrc/Protocols/MapemSpatem/spatem_codec.hh @@ -1,18 +1,18 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "spatem_pdu_codec.hh" - -#include "mapem_spatem_types.hh" - -class spatem_codec : public codec { - spatem_pdu_codec asn_codec; - -public: - explicit spatem_codec() : codec(), asn_codec(){}; - virtual ~spatem_codec(){}; - - virtual int encode(const SPATEM__PDU__Descriptions::SPATEM &spatem, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, SPATEM__PDU__Descriptions::SPATEM &, params *params = NULL); -}; // End of class spatem_codec +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "spatem_pdu_codec.hh" + +#include "mapem_spatem_types.hh" + +class spatem_codec : public codec { + spatem_pdu_codec asn_codec; + +public: + explicit spatem_codec() : codec(), asn_codec(){}; + virtual ~spatem_codec(){}; + + virtual int encode(const SPATEM__PDU__Descriptions::SPATEM &spatem, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, SPATEM__PDU__Descriptions::SPATEM &, params *params = NULL); +}; // End of class spatem_codec diff --git a/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.cc b/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.cc index be3657bb0841d49297015b028374d976f8d31583..125685040ef43e1c754cb9c66d402635af886734 100644 --- a/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.cc +++ b/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.cc @@ -1,16 +1,16 @@ -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" -#include "mapem_spatem_types.hh" -#include "spatem_codec.hh" - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_SPATEM; -} - -int spatem_pdu_codec::encode(const SPATEM__PDU__Descriptions::SPATEM &p_spatem, BITSTRING &p_data) { - return _encode(SPATEM__PDU__Descriptions::SPATEM_descr_, asn_DEF_SPATEM, p_spatem, p_data); -} - -int spatem_pdu_codec::decode(const BITSTRING &p_data, SPATEM__PDU__Descriptions::SPATEM &p_spatem) { - return _decode(SPATEM__PDU__Descriptions::SPATEM_descr_, asn_DEF_SPATEM, p_data, p_spatem); -} +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" +#include "mapem_spatem_types.hh" +#include "spatem_codec.hh" + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_SPATEM; +} + +int spatem_pdu_codec::encode(const SPATEM__PDU__Descriptions::SPATEM &p_spatem, BITSTRING &p_data) { + return _encode(SPATEM__PDU__Descriptions::SPATEM_descr_, asn_DEF_SPATEM, p_spatem, p_data); +} + +int spatem_pdu_codec::decode(const BITSTRING &p_data, SPATEM__PDU__Descriptions::SPATEM &p_spatem) { + return _decode(SPATEM__PDU__Descriptions::SPATEM_descr_, asn_DEF_SPATEM, p_data, p_spatem); +} diff --git a/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.hh b/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.hh index dd9874fe6ec7d085099f634077f12076b66694dc..aec11246df374bdb9e8c6f69688f70abee58101e 100644 --- a/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.hh +++ b/ccsrc/Protocols/MapemSpatem/spatem_pdu_codec.hh @@ -1,14 +1,14 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -#include "mapem_spatem_types.hh" - -class spatem_pdu_codec : public per_codec { -public: - explicit spatem_pdu_codec(){}; - virtual int encode(const SPATEM__PDU__Descriptions::SPATEM &spatem, BITSTRING &data); - virtual int decode(const BITSTRING &data, SPATEM__PDU__Descriptions::SPATEM &); -}; // End of class spatem_pdu_codec +#pragma once + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +#include "mapem_spatem_types.hh" + +class spatem_pdu_codec : public per_codec { +public: + explicit spatem_pdu_codec(){}; + virtual int encode(const SPATEM__PDU__Descriptions::SPATEM &spatem, BITSTRING &data); + virtual int decode(const BITSTRING &data, SPATEM__PDU__Descriptions::SPATEM &); +}; // End of class spatem_pdu_codec diff --git a/ccsrc/Protocols/Pcap/module.mk b/ccsrc/Protocols/Pcap/module.mk index 0f6495fd1f97d7dc021967cfb0ba521696060c50..0bb74313a4428f9608e2b6b1af896a4204093a90 100644 --- a/ccsrc/Protocols/Pcap/module.mk +++ b/ccsrc/Protocols/Pcap/module.mk @@ -1,3 +1,3 @@ -sources := pcap_cygwin_layer.cc pcap_layer.cc pcap_linux_layer.cc pcap_offline_layer.cc -includes := . - +sources := pcap_cygwin_layer.cc pcap_layer.cc pcap_linux_layer.cc pcap_offline_layer.cc +includes := . + diff --git a/ccsrc/Protocols/Pcap/pcap_cygwin_layer.cc b/ccsrc/Protocols/Pcap/pcap_cygwin_layer.cc index 03ef148342e022a27ea4ed32fa81cb30a5339ed8..2a8ce95b0b961b06b3561d4e49ac4f90fb166cd9 100644 --- a/ccsrc/Protocols/Pcap/pcap_cygwin_layer.cc +++ b/ccsrc/Protocols/Pcap/pcap_cygwin_layer.cc @@ -1,265 +1,265 @@ -#if defined(__CYGWIN__) - -#define _GNU_SOURCE - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "pcap_layer_factory.hh" - -#include "loggers.hh" - -#include - -typedef struct { - bpf_int32 tv_sec; /* seconds */ - bpf_int32 tv_usec; /* microseconds */ -} pcap_o_timeval; - -typedef struct pcap_o_pkthdr { - pcap_o_timeval ts; /* time stamp */ - bpf_u_int32 caplen; /* length of portion present */ - bpf_u_int32 len; /* length this packet (off wire) */ -} pcap_o_pkthdr; - -extern "C" int pcap_oid_get_request(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp); - -static const char *_hexDigits = "0123456789ABCDEF"; -static char * _bin2hex(char *hex, size_t hlen, const char *bin, size_t blen) { - const unsigned char *b, *e; - char * s; - - // sanity check - if (hlen >= 0 && hlen < blen * 2) - return NULL; - - b = (const unsigned char *)bin; - e = b + blen - 1; - s = hex + blen * 2; - if (s < hex + hlen) - *s = 0; - for (; b <= e; e--) { - *(--s) = _hexDigits[(*e) & 0xF]; - *(--s) = _hexDigits[(*e) >> 4]; - } - return hex + blen * 2; -} - -pcap_layer::pcap_layer(const std::string &p_type, const std::string ¶m) - : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _running(FALSE), _time_key("pcap_layer::Handle_Fd_Event_Readable") { - loggers::get_instance().log(">>> pcap_layer::pcap_layer: %s, %s", p_type.c_str(), param.c_str()); - params::convert(_params, param); - - char error_buffer[PCAP_ERRBUF_SIZE]; - params::const_iterator it; - std::string nic; // network interface name - bpf_u_int32 mask; // subnet mask - bpf_u_int32 net; // ip address - - it = _params.find(params::nic); - if ((it == _params.end()) || it->second.empty()) { - loggers::get_instance().error("pcap_layer::pcap_layer: NIC must be specified"); - return; - } - - nic = std::string("\\Device\\NPF_{") + it->second + "}"; - - if (pcap_lookupnet(nic.c_str(), &net, &mask, error_buffer) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: pcap_layer::pcap_layer: Failed to fetch newtork address for device %s", nic.c_str()); - } - loggers::get_instance().log("pcap_layer::pcap_layer: Device %s Network address: %d", nic.c_str(), net); - - // Open the device - _device = pcap_open_live(nic.c_str(), 65536 /*64*1024*/, 1, 100, error_buffer); - if (_device == NULL) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open device %s", nic.c_str()); - return; - } - - // Setup filter - std::string filter = ""; - std::string mac_src; - it = _params.find(params::mac_src); - if (it != _params.end() && !it->second.empty()) { - mac_src = it->second; - } else { - // Not found - // determine it automatically -#ifndef OID_802_3_CURRENT_ADDRESS -#define OID_802_3_CURRENT_ADDRESS 0x01010102 -#endif - char mac[6] = {0}; - size_t l = sizeof(mac); - pcap_oid_get_request(_device, OID_802_3_CURRENT_ADDRESS, mac, &l); - char buf[13]; - *_bin2hex(buf, sizeof(buf), mac, 6) = 0; - mac_src = buf; - loggers::get_instance().user("pcap_layer::pcap_layer: local MAC is %s", mac_src.c_str()); - _params[params::mac_src] = mac_src; - } - - std::string mac_bc; - it = _params.find(params::mac_bc); - if (it != _params.end() && !it->second.empty()) - mac_bc = it->second; - else - mac_bc = "ffffffffffff"; - - if (mac_bc == mac_src || mac_src.empty()) - filter = "ether dst " + mac_bc; - else - filter = "( ether dst " + mac_bc + " or ether dst " + mac_src + " )"; - - if (!mac_src.empty()) - // Reject ITS messages sent by this component - filter += " and not ether src " + mac_src; - - // Add user defined filter - it = _params.find(std::string("filter")); - if ((it != _params.end()) && !it->second.empty()) { - filter += std::string(" ") + it->second; - } - - // Log final PCAP filter - loggers::get_instance().user("pcap_layer::pcap_layer: Filter: %s", filter.c_str()); - - // setup filter - { - struct bpf_program f = {0}; - if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to compile PCAP filter"); - } else { - if (pcap_setfilter(_device, &f) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set PCAP filter"); - } - } - pcap_freecode(&f); - } - - _o_params.insert(std::pair(std::string("timestamp"), std::string())); - - // create pipe and run thread - if (pipe2(_fd, O_NONBLOCK) == -1) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to create a pipe: %s", ::strerror(errno)); - } - // Pass the pipe handler to the polling procedure - loggers::get_instance().log("pcap_layer::pcap_layer: Call handler with descriptor %d", _fd[0]); - Handler_Add_Fd_Read(_fd[0]); - - // Create the reader thread - _thread = new std::thread(&pcap_layer::run, (void *)this); - if (_thread == NULL) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to start offline thread"); - } - while (_running == FALSE) { - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - // Thread was started - loggers::get_instance().log("<<< pcap_layer::pcap_layer"); -} // End of ctor - -pcap_layer::~pcap_layer() { - loggers::get_instance().log(">>> pcap_layer::~pcap_layer"); - - if (_device != NULL) { - if (_thread != NULL) { - _running = FALSE; - // Wait for the working thread to terminate - _thread->join(); - loggers::get_instance().log("pcap_layer::~pcap_layer: Thread were stops"); - // Cleanup - delete _thread; - close(_fd[0]); - close(_fd[1]); - } - pcap_close(_device); - } -} // End of dtor - -void *pcap_layer::run(void *p_this) { - pcap_layer &p = *static_cast(p_this); - return p.thread(); -} - -void *pcap_layer::thread() { - pcap_o_pkthdr *pkt_header; - const u_char * pkt_data; - unsigned char pkt_count = 0; - - // loggers::get_instance().log(">>> pcap_layer::run"); - - _running = TRUE; - - // wait a bit before sending first packet - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - - while (_running) { // Loop while _running flag is up - // get next frame - int result = pcap_next_ex(_device, (struct pcap_pkthdr **)&pkt_header, &pkt_data); - if (result == 0) { - continue; - } - if (result < 0) { - // loggers::get_instance().log("<<< pcap_layer::run: error %s", pcap_geterr(_device)); - break; - } - - while (_running && !_resume.try_lock()) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } -#if 0 - { - char buf[128]; - std::time_t t = pkt_header->ts.tv_sec; - std::tm * pt = std::localtime( &t ); - t = std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", pt); - std::sprintf(buf+t, "%ld", pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)); // Use milliseconds - _o_params[params::timestamp] = std::string(buf); - } -#else - _o_params[params::timestamp] = std::to_string(pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)); // Use milliseconds -#endif - _o_data = OCTETSTRING(pkt_header->len, pkt_data); - write(_fd[1], &pkt_count, 1); - pkt_count++; - } - _running = FALSE; - // loggers::get_instance().log("<<< pcap_layer::run"); - return NULL; -} - -void pcap_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> pcap_layer::send_data: ", data); - if (pcap_sendpacket(_device, static_cast(data), data.lengthof()) == -1) { - loggers::get_instance().error("pcap_layer::send_data: Failed to send packet: %s", pcap_geterr(_device)); - } -} - -void pcap_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> pcap_layer::receive_data: Received %d bytes", data.lengthof()); - loggers::get_instance().log_to_hexa("Packet dump", data); - - // Pass the packet to the upper layers - receive_to_all_layers(data, params); -} - -void pcap_layer::Handle_Fd_Event_Readable(int fd) { - char c[2]; - float duration; - loggers::get_instance().set_start_time(_time_key); - this->receive_data(_o_data, _o_params); - loggers::get_instance().set_stop_time(_time_key, duration); - read(_fd[0], &c, 1); - _resume.unlock(); -} - -pcap_layer_factory pcap_layer_factory::_f; - -#endif //__CYGWIN__ +#if defined(__CYGWIN__) + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "pcap_layer_factory.hh" + +#include "loggers.hh" + +#include + +typedef struct { + bpf_int32 tv_sec; /* seconds */ + bpf_int32 tv_usec; /* microseconds */ +} pcap_o_timeval; + +typedef struct pcap_o_pkthdr { + pcap_o_timeval ts; /* time stamp */ + bpf_u_int32 caplen; /* length of portion present */ + bpf_u_int32 len; /* length this packet (off wire) */ +} pcap_o_pkthdr; + +extern "C" int pcap_oid_get_request(pcap_t *p, bpf_u_int32 oid, void *data, size_t *lenp); + +static const char *_hexDigits = "0123456789ABCDEF"; +static char * _bin2hex(char *hex, size_t hlen, const char *bin, size_t blen) { + const unsigned char *b, *e; + char * s; + + // sanity check + if (hlen >= 0 && hlen < blen * 2) + return NULL; + + b = (const unsigned char *)bin; + e = b + blen - 1; + s = hex + blen * 2; + if (s < hex + hlen) + *s = 0; + for (; b <= e; e--) { + *(--s) = _hexDigits[(*e) & 0xF]; + *(--s) = _hexDigits[(*e) >> 4]; + } + return hex + blen * 2; +} + +pcap_layer::pcap_layer(const std::string &p_type, const std::string ¶m) + : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _running(FALSE), _time_key("pcap_layer::Handle_Fd_Event_Readable") { + loggers::get_instance().log(">>> pcap_layer::pcap_layer: %s, %s", p_type.c_str(), param.c_str()); + params::convert(_params, param); + + char error_buffer[PCAP_ERRBUF_SIZE]; + params::const_iterator it; + std::string nic; // network interface name + bpf_u_int32 mask; // subnet mask + bpf_u_int32 net; // ip address + + it = _params.find(params::nic); + if ((it == _params.end()) || it->second.empty()) { + loggers::get_instance().error("pcap_layer::pcap_layer: NIC must be specified"); + return; + } + + nic = std::string("\\Device\\NPF_{") + it->second + "}"; + + if (pcap_lookupnet(nic.c_str(), &net, &mask, error_buffer) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: pcap_layer::pcap_layer: Failed to fetch newtork address for device %s", nic.c_str()); + } + loggers::get_instance().log("pcap_layer::pcap_layer: Device %s Network address: %d", nic.c_str(), net); + + // Open the device + _device = pcap_open_live(nic.c_str(), 65536 /*64*1024*/, 1, 100, error_buffer); + if (_device == NULL) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open device %s", nic.c_str()); + return; + } + + // Setup filter + std::string filter = ""; + std::string mac_src; + it = _params.find(params::mac_src); + if (it != _params.end() && !it->second.empty()) { + mac_src = it->second; + } else { + // Not found + // determine it automatically +#ifndef OID_802_3_CURRENT_ADDRESS +#define OID_802_3_CURRENT_ADDRESS 0x01010102 +#endif + char mac[6] = {0}; + size_t l = sizeof(mac); + pcap_oid_get_request(_device, OID_802_3_CURRENT_ADDRESS, mac, &l); + char buf[13]; + *_bin2hex(buf, sizeof(buf), mac, 6) = 0; + mac_src = buf; + loggers::get_instance().user("pcap_layer::pcap_layer: local MAC is %s", mac_src.c_str()); + _params[params::mac_src] = mac_src; + } + + std::string mac_bc; + it = _params.find(params::mac_bc); + if (it != _params.end() && !it->second.empty()) + mac_bc = it->second; + else + mac_bc = "ffffffffffff"; + + if (mac_bc == mac_src || mac_src.empty()) + filter = "ether dst " + mac_bc; + else + filter = "( ether dst " + mac_bc + " or ether dst " + mac_src + " )"; + + if (!mac_src.empty()) + // Reject ITS messages sent by this component + filter += " and not ether src " + mac_src; + + // Add user defined filter + it = _params.find(std::string("filter")); + if ((it != _params.end()) && !it->second.empty()) { + filter += std::string(" ") + it->second; + } + + // Log final PCAP filter + loggers::get_instance().user("pcap_layer::pcap_layer: Filter: %s", filter.c_str()); + + // setup filter + { + struct bpf_program f = {0}; + if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to compile PCAP filter"); + } else { + if (pcap_setfilter(_device, &f) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set PCAP filter"); + } + } + pcap_freecode(&f); + } + + _o_params.insert(std::pair(std::string("timestamp"), std::string())); + + // create pipe and run thread + if (pipe2(_fd, O_NONBLOCK) == -1) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to create a pipe: %s", ::strerror(errno)); + } + // Pass the pipe handler to the polling procedure + loggers::get_instance().log("pcap_layer::pcap_layer: Call handler with descriptor %d", _fd[0]); + Handler_Add_Fd_Read(_fd[0]); + + // Create the reader thread + _thread = new std::thread(&pcap_layer::run, (void *)this); + if (_thread == NULL) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to start offline thread"); + } + while (_running == FALSE) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + // Thread was started + loggers::get_instance().log("<<< pcap_layer::pcap_layer"); +} // End of ctor + +pcap_layer::~pcap_layer() { + loggers::get_instance().log(">>> pcap_layer::~pcap_layer"); + + if (_device != NULL) { + if (_thread != NULL) { + _running = FALSE; + // Wait for the working thread to terminate + _thread->join(); + loggers::get_instance().log("pcap_layer::~pcap_layer: Thread were stops"); + // Cleanup + delete _thread; + close(_fd[0]); + close(_fd[1]); + } + pcap_close(_device); + } +} // End of dtor + +void *pcap_layer::run(void *p_this) { + pcap_layer &p = *static_cast(p_this); + return p.thread(); +} + +void *pcap_layer::thread() { + pcap_o_pkthdr *pkt_header; + const u_char * pkt_data; + unsigned char pkt_count = 0; + + // loggers::get_instance().log(">>> pcap_layer::run"); + + _running = TRUE; + + // wait a bit before sending first packet + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + + while (_running) { // Loop while _running flag is up + // get next frame + int result = pcap_next_ex(_device, (struct pcap_pkthdr **)&pkt_header, &pkt_data); + if (result == 0) { + continue; + } + if (result < 0) { + // loggers::get_instance().log("<<< pcap_layer::run: error %s", pcap_geterr(_device)); + break; + } + + while (_running && !_resume.try_lock()) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +#if 0 + { + char buf[128]; + std::time_t t = pkt_header->ts.tv_sec; + std::tm * pt = std::localtime( &t ); + t = std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", pt); + std::sprintf(buf+t, "%ld", pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)); // Use milliseconds + _o_params[params::timestamp] = std::string(buf); + } +#else + _o_params[params::timestamp] = std::to_string(pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)); // Use milliseconds +#endif + _o_data = OCTETSTRING(pkt_header->len, pkt_data); + write(_fd[1], &pkt_count, 1); + pkt_count++; + } + _running = FALSE; + // loggers::get_instance().log("<<< pcap_layer::run"); + return NULL; +} + +void pcap_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> pcap_layer::send_data: ", data); + if (pcap_sendpacket(_device, static_cast(data), data.lengthof()) == -1) { + loggers::get_instance().error("pcap_layer::send_data: Failed to send packet: %s", pcap_geterr(_device)); + } +} + +void pcap_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> pcap_layer::receive_data: Received %d bytes", data.lengthof()); + loggers::get_instance().log_to_hexa("Packet dump", data); + + // Pass the packet to the upper layers + receive_to_all_layers(data, params); +} + +void pcap_layer::Handle_Fd_Event_Readable(int fd) { + char c[2]; + float duration; + loggers::get_instance().set_start_time(_time_key); + this->receive_data(_o_data, _o_params); + loggers::get_instance().set_stop_time(_time_key, duration); + read(_fd[0], &c, 1); + _resume.unlock(); +} + +pcap_layer_factory pcap_layer_factory::_f; + +#endif //__CYGWIN__ diff --git a/ccsrc/Protocols/Pcap/pcap_cygwin_layer.hh b/ccsrc/Protocols/Pcap/pcap_cygwin_layer.hh index 3e9fc0de70dcb71853f941ac158671191025e614..d7d477a871c179fba588758188722f63e8bf1712 100644 --- a/ccsrc/Protocols/Pcap/pcap_cygwin_layer.hh +++ b/ccsrc/Protocols/Pcap/pcap_cygwin_layer.hh @@ -1,79 +1,79 @@ -/*! - * \file pcap_layer.hh - * \brief Header file for ITS Offline Pcap port layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include - -#include "params.hh" -#include "t_layer.hh" - -#include - -class PORT; //! Forward declaration of TITAN class - -typedef struct pcap pcap_t; - -/*! - * \class pcap_layer - * \brief This class provides description of ITS PCAP port protocol layer - */ -class pcap_layer : public layer, public PORT { - - params _params; //! Layer parameters - pcap_t * _device; //! Device handle - std::thread *_thread; //! Thread handle, used to read PCAP file instead of NIC, used in file mode - std::mutex _resume; - bool _running; //! Set to true when the thread is running, used in file mode - int _fd[2]; //! pipe to signal to Titan - - OCTETSTRING _o_data; - params _o_params; - - std::string _time_key; - - static void *run(void *p_this); - -public: - void *thread(void); - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the pcap_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - pcap_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~pcap_layer(); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - void Handle_Fd_Event_Readable(int fd); -}; +/*! + * \file pcap_layer.hh + * \brief Header file for ITS Offline Pcap port layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include + +#include "params.hh" +#include "t_layer.hh" + +#include + +class PORT; //! Forward declaration of TITAN class + +typedef struct pcap pcap_t; + +/*! + * \class pcap_layer + * \brief This class provides description of ITS PCAP port protocol layer + */ +class pcap_layer : public layer, public PORT { + + params _params; //! Layer parameters + pcap_t * _device; //! Device handle + std::thread *_thread; //! Thread handle, used to read PCAP file instead of NIC, used in file mode + std::mutex _resume; + bool _running; //! Set to true when the thread is running, used in file mode + int _fd[2]; //! pipe to signal to Titan + + OCTETSTRING _o_data; + params _o_params; + + std::string _time_key; + + static void *run(void *p_this); + +public: + void *thread(void); + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the pcap_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + pcap_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~pcap_layer(); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + void Handle_Fd_Event_Readable(int fd); +}; diff --git a/ccsrc/Protocols/Pcap/pcap_layer.cc b/ccsrc/Protocols/Pcap/pcap_layer.cc index b88a666197154c1760f0bdb7a30fd2fc3074a21c..218fc711483e1ddc17e72a4545f08e6a28f25207 100644 --- a/ccsrc/Protocols/Pcap/pcap_layer.cc +++ b/ccsrc/Protocols/Pcap/pcap_layer.cc @@ -1,276 +1,276 @@ -#if 0 -#include -#include -#include -#include -#include - -#include - -#include "pcap_layer_factory.hh" - -typedef struct pcap_pkthdr pcap_o_pkthdr; -typedef struct timeval pcap_o_timeval; - -#include "loggers.hh" - -pcap_layer::pcap_layer(const std::string& p_type, const std::string& param) : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _pcap_h(-1), _thread(NULL), _running(FALSE), _resume(), _sent_file(NULL), _time_key("pcap_layer::Handle_Fd_Event_Readable") { - bool online = false; - loggers::get_instance().log(">>> pcap_layer::pcap_layer: %s, %s", to_string().c_str(), param.c_str()); - _fd[0] = -1; _fd[1] = -1; - // Setup parameters - params::convert(_params, param); - //_params.log(); - // Prepare capture processing - char error_buffer[PCAP_ERRBUF_SIZE]; - params::const_iterator it = _params.find(params::nic); - if ((it != _params.end()) && !it->second.empty()) { // Use online capture - // Fetch the network address and network mask - bpf_u_int32 mask; // subnet mask - bpf_u_int32 net; // ip address - std::string nic; - online = true; - nic = _params[params::nic]; - if (pcap_lookupnet(nic.c_str(), &net, &mask, error_buffer) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: pcap_layer::pcap_layer: Failed to fetch newtork address for device %s", nic.c_str()); - } - loggers::get_instance().log("pcap_layer::pcap_layer: Device %s Network address: %d", nic.c_str(), net); - // Open the device - _device = pcap_open_live(nic.c_str(), 65536, 1, 1000, error_buffer); // TODO Replace hard coded values by pcap_layer:: - if (_device == NULL) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open device %s", nic.c_str()); - } // else, continue - // Set non-blocking flag for the polling procedure - if (pcap_setnonblock(_device, 1, error_buffer) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set blocking mode: %s", error_buffer); - } - // Retrieve the device file handler - _pcap_h = pcap_get_selectable_fd(_device); - if (_pcap_h == -1) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to get device handler"); - } - } else { - // Check file name - it = _params.find(std::string("file")); - if ((it != _params.cend()) && !it->second.empty()) { // Use offline capture - struct stat s = {0}; - if ((stat(_params["file"].c_str(), &s) != 0) || !S_ISREG(s.st_mode)) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to acces PCAP file %s", _params["file"].c_str()); - } - // File exist, open it - _device = pcap_open_offline(_params["file"].c_str(), error_buffer); - if (_device == NULL) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open PCAP file %s", error_buffer); - } // else, continue - // Create the dump file for the sent packet based on the openned file name and the current time in milliseconds - it = _params.find("save_mode"); - if ((it != _params.cend()) && (it->second.compare("1") == 0)) { - unsigned long ms = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1); - std::string ext("_" + std::to_string(ms)); - int i = _params["file"].find(".pcap"); - if (i > 0) { - std::string f(_params["file"].substr(0, i) + ext + ".pcap"); - loggers::get_instance().log("pcap_layer::pcap_layer: Save file name: %s", f.c_str()); - if ((_sent_file = pcap_dump_open(_device, f.c_str())) == NULL) { - loggers::get_instance().warning("pcap_layer::pcap_layer: Failed to open save file %s", f.c_str()); - } - } - } // else, nothing to do - } else { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open PCAP file %s", error_buffer); - } - } - - // Setup filter - std::string filter = ""; - it = _params.find(params::mac_src); - if (it == _params.end()) { // Not found - loggers::get_instance().error("pcap_layer::pcap_layer: mac_src parameter not found, cannot continue"); - } else { - // Reject ITS messages sent by this component - filter = "not ether src " + _params[params::mac_src]; - // Accept ITS broadcasted to this componenet - filter += " and (ether dst " + _params[params::mac_src]; - // Accept ITS broadcasted messages - it = _params.find(params::mac_bc); - if ((it != _params.end()) && !it->second.empty()) { - filter += " or ether dst " + it->second + ")"; - } else { - filter += " or ether dst ffffffffffff) "; - } - // Add user defined filter - it = _params.find(std::string("filter")); - if ((it != _params.end()) && !it->second.empty()) { - filter += _params["filter"]; - } // else nothing to do - } - // Log final PCAP filter - loggers::get_instance().user("pcap_layer::pcap_layer: Filter: %s", filter.c_str()); - if (!filter.empty()) { - struct bpf_program f = {0}; - if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to compile PCAP filter"); - } - if (pcap_setfilter(_device, &f) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set PCAP filter"); - } - pcap_freecode(&f); - } - - // Pass the device file handler to the polling procedure - if (_pcap_h != -1) { // Live capture - Handler_Add_Fd_Read(_pcap_h); - } else { // Offline capture or cygwin - // Create a pipe - if (pipe2(_fd, O_NONBLOCK) == -1) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to create a pipe: %s", ::strerror(errno)); - } - if(online){ - _pcap_h = _fd[0]; - } - // Pass the pipe handler to the polling procedure - loggers::get_instance().log("pcap_layer::pcap_layer: Call handler with descriptor %d", _fd[0]); - Handler_Add_Fd_Read(_fd[0]); - // Create the offline reader thread - _thread = new std::thread(&pcap_layer::run, (void *)this); - if (_thread == NULL) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to start offline thread"); - } - // Start it to dispatch packet to a pipe - while (_running == FALSE) { - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - // Thread was started - loggers::get_instance().log("<<< pcap_layer::pcap_layer"); - } -} // End of ctor - -pcap_layer::~pcap_layer() { - loggers::get_instance().log(">>> pcap_layer::~pcap_layer"); - - if (_device != NULL) { - if (_thread != NULL) { - _running = FALSE; - // Wait for the working thread to terminate - _thread->join(); - loggers::get_instance().log("pcap_layer::~pcap_layer: Thread were stops"); - // Cleanup - delete _thread; - close(_fd[0]); - close(_fd[1]); - } - if (_sent_file != NULL) { - pcap_dump_close(_sent_file); - } - pcap_close(_device); - } -} // End of dtor - -void* pcap_layer::run(void* p_this) { - pcap_layer& p = *static_cast(p_this); - return p.thread(); -} - -void* pcap_layer::thread() { - loggers::get_instance().log(">>> pcap_layer::run"); - - // Wait a little bit before to start sending packet - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - params::const_iterator it = _params.find("frame_offset"); - if ((it != _params.cend()) && (it->second.compare("0") != 0)) { - // TODO Try t use PCAP filter to start directly to the correct frame offset - /*try { - unsigned int offset = std::stoul(str_dec, &s); - // Skip frames - struct pcap_pkthdr *pkt_header; - const u_char *pkt_data; - int result = pcap_next_ex(_device, &pkt_header, &pkt_data); - if (result == 1) { // Succeed - } - } - catch (invalid_argument& i) { - } - catch (out_of_range& o) { - }*/ - } - // Let's go - _running = TRUE; - while (_running) { // Loop while _running flag is up - if (_resume.try_lock() == TRUE) { // Previous packet was consumed, lock for the next one - write(_fd[1], "\n", 1); // Any character will do the job - } else { // not ready yet - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - } - - loggers::get_instance().log("<<< pcap_layer::run"); - return NULL; -} - -void pcap_layer::send_data(OCTETSTRING& data, params& params) { - loggers::get_instance().log_msg(">>> pcap_layer::send_data: ", data); - - if (_pcap_h != -1) { // Check if offline mode is used - if (pcap_sendpacket(_device, static_cast(data), data.lengthof()) == -1) { - loggers::get_instance().error("pcap_layer::send_data: Failed to send packet: %s", pcap_geterr(_device)); - } - } else if (_sent_file != NULL) { - struct pcap_pkthdr hdr; - std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); - std::chrono::milliseconds ms = std::chrono::duration_cast(now.time_since_epoch()); - hdr.ts.tv_sec = ms.count() / 1000; - hdr.ts.tv_usec = (ms.count() % 1000) * 1000; - hdr.caplen = data.lengthof(); - hdr.len = hdr.caplen; - pcap_dump((u_char *)_sent_file, &hdr, static_cast(data)); - } else { - loggers::get_instance().log("pcap_layer::send_data: Offline mode, operation was skipped"); - } -} - -void pcap_layer::receive_data(OCTETSTRING& data, params& params) { - loggers::get_instance().log(">>> pcap_layer::receive_data: Received %d bytes", data.lengthof()); - loggers::get_instance().log_to_hexa("Packet dump", data); - - // Pass the packet to the upper layers - receive_to_all_layers(data, params); -} - -void pcap_layer::Handle_Fd_Event_Readable(int fd) { - //loggers::get_instance().log(">>> pcap_layer::Handle_Fd_Event_Readable: %d", fd); - - pcap_o_pkthdr *pkt_header; - const u_char *pkt_data; - int result = pcap_next_ex(_device, (struct pcap_pkthdr**)&pkt_header, &pkt_data); - if (result == 1) { // Succeed - if (pkt_header->caplen > 14) { // Reject too small packet - //loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: %ld - % ld - %d", pkt_header->ts.tv_sec, pkt_header->ts.tv_usec, pkt_header->len); - // Fill parameters from PCAP layer - params params; - params.insert(std::pair(params::timestamp, std::to_string(pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)))); // Use milliseconds - // Process the packet at this layer - OCTETSTRING os(pkt_header->caplen, pkt_data); - //loggers::get_instance().log_to_hexa("pcap_layer::Handle_Fd_Event_Readable: ", os); - // TODO Case of caplen != len !!! - float duration; - loggers::get_instance().set_start_time(_time_key); - this->receive_data(os, params); // TODO Check execution time for decoding operation - loggers::get_instance().set_stop_time(_time_key, duration); - } - } // else, skip the packet - // Specific to offline mode - if (_fd[0] != -1) { // Check if offline mode is used - //loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: Read pipe"); - char c[2]; - read(_fd[0], &c, 1); - if (result == -2) { // End of file, therminate worker thread - _running = FALSE; - } - //loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: pcap_next_ex failed: result=%d", result); - _resume.unlock(); - } // else, nothing to do -} - -pcap_layer_factory pcap_layer_factory::_f; - -#endif // !CYGWIN +#if 0 +#include +#include +#include +#include +#include + +#include + +#include "pcap_layer_factory.hh" + +typedef struct pcap_pkthdr pcap_o_pkthdr; +typedef struct timeval pcap_o_timeval; + +#include "loggers.hh" + +pcap_layer::pcap_layer(const std::string& p_type, const std::string& param) : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _pcap_h(-1), _thread(NULL), _running(FALSE), _resume(), _sent_file(NULL), _time_key("pcap_layer::Handle_Fd_Event_Readable") { + bool online = false; + loggers::get_instance().log(">>> pcap_layer::pcap_layer: %s, %s", to_string().c_str(), param.c_str()); + _fd[0] = -1; _fd[1] = -1; + // Setup parameters + params::convert(_params, param); + //_params.log(); + // Prepare capture processing + char error_buffer[PCAP_ERRBUF_SIZE]; + params::const_iterator it = _params.find(params::nic); + if ((it != _params.end()) && !it->second.empty()) { // Use online capture + // Fetch the network address and network mask + bpf_u_int32 mask; // subnet mask + bpf_u_int32 net; // ip address + std::string nic; + online = true; + nic = _params[params::nic]; + if (pcap_lookupnet(nic.c_str(), &net, &mask, error_buffer) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: pcap_layer::pcap_layer: Failed to fetch newtork address for device %s", nic.c_str()); + } + loggers::get_instance().log("pcap_layer::pcap_layer: Device %s Network address: %d", nic.c_str(), net); + // Open the device + _device = pcap_open_live(nic.c_str(), 65536, 1, 1000, error_buffer); // TODO Replace hard coded values by pcap_layer:: + if (_device == NULL) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open device %s", nic.c_str()); + } // else, continue + // Set non-blocking flag for the polling procedure + if (pcap_setnonblock(_device, 1, error_buffer) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set blocking mode: %s", error_buffer); + } + // Retrieve the device file handler + _pcap_h = pcap_get_selectable_fd(_device); + if (_pcap_h == -1) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to get device handler"); + } + } else { + // Check file name + it = _params.find(std::string("file")); + if ((it != _params.cend()) && !it->second.empty()) { // Use offline capture + struct stat s = {0}; + if ((stat(_params["file"].c_str(), &s) != 0) || !S_ISREG(s.st_mode)) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to acces PCAP file %s", _params["file"].c_str()); + } + // File exist, open it + _device = pcap_open_offline(_params["file"].c_str(), error_buffer); + if (_device == NULL) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open PCAP file %s", error_buffer); + } // else, continue + // Create the dump file for the sent packet based on the openned file name and the current time in milliseconds + it = _params.find("save_mode"); + if ((it != _params.cend()) && (it->second.compare("1") == 0)) { + unsigned long ms = std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1); + std::string ext("_" + std::to_string(ms)); + int i = _params["file"].find(".pcap"); + if (i > 0) { + std::string f(_params["file"].substr(0, i) + ext + ".pcap"); + loggers::get_instance().log("pcap_layer::pcap_layer: Save file name: %s", f.c_str()); + if ((_sent_file = pcap_dump_open(_device, f.c_str())) == NULL) { + loggers::get_instance().warning("pcap_layer::pcap_layer: Failed to open save file %s", f.c_str()); + } + } + } // else, nothing to do + } else { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open PCAP file %s", error_buffer); + } + } + + // Setup filter + std::string filter = ""; + it = _params.find(params::mac_src); + if (it == _params.end()) { // Not found + loggers::get_instance().error("pcap_layer::pcap_layer: mac_src parameter not found, cannot continue"); + } else { + // Reject ITS messages sent by this component + filter = "not ether src " + _params[params::mac_src]; + // Accept ITS broadcasted to this componenet + filter += " and (ether dst " + _params[params::mac_src]; + // Accept ITS broadcasted messages + it = _params.find(params::mac_bc); + if ((it != _params.end()) && !it->second.empty()) { + filter += " or ether dst " + it->second + ")"; + } else { + filter += " or ether dst ffffffffffff) "; + } + // Add user defined filter + it = _params.find(std::string("filter")); + if ((it != _params.end()) && !it->second.empty()) { + filter += _params["filter"]; + } // else nothing to do + } + // Log final PCAP filter + loggers::get_instance().user("pcap_layer::pcap_layer: Filter: %s", filter.c_str()); + if (!filter.empty()) { + struct bpf_program f = {0}; + if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to compile PCAP filter"); + } + if (pcap_setfilter(_device, &f) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set PCAP filter"); + } + pcap_freecode(&f); + } + + // Pass the device file handler to the polling procedure + if (_pcap_h != -1) { // Live capture + Handler_Add_Fd_Read(_pcap_h); + } else { // Offline capture or cygwin + // Create a pipe + if (pipe2(_fd, O_NONBLOCK) == -1) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to create a pipe: %s", ::strerror(errno)); + } + if(online){ + _pcap_h = _fd[0]; + } + // Pass the pipe handler to the polling procedure + loggers::get_instance().log("pcap_layer::pcap_layer: Call handler with descriptor %d", _fd[0]); + Handler_Add_Fd_Read(_fd[0]); + // Create the offline reader thread + _thread = new std::thread(&pcap_layer::run, (void *)this); + if (_thread == NULL) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to start offline thread"); + } + // Start it to dispatch packet to a pipe + while (_running == FALSE) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + // Thread was started + loggers::get_instance().log("<<< pcap_layer::pcap_layer"); + } +} // End of ctor + +pcap_layer::~pcap_layer() { + loggers::get_instance().log(">>> pcap_layer::~pcap_layer"); + + if (_device != NULL) { + if (_thread != NULL) { + _running = FALSE; + // Wait for the working thread to terminate + _thread->join(); + loggers::get_instance().log("pcap_layer::~pcap_layer: Thread were stops"); + // Cleanup + delete _thread; + close(_fd[0]); + close(_fd[1]); + } + if (_sent_file != NULL) { + pcap_dump_close(_sent_file); + } + pcap_close(_device); + } +} // End of dtor + +void* pcap_layer::run(void* p_this) { + pcap_layer& p = *static_cast(p_this); + return p.thread(); +} + +void* pcap_layer::thread() { + loggers::get_instance().log(">>> pcap_layer::run"); + + // Wait a little bit before to start sending packet + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + params::const_iterator it = _params.find("frame_offset"); + if ((it != _params.cend()) && (it->second.compare("0") != 0)) { + // TODO Try t use PCAP filter to start directly to the correct frame offset + /*try { + unsigned int offset = std::stoul(str_dec, &s); + // Skip frames + struct pcap_pkthdr *pkt_header; + const u_char *pkt_data; + int result = pcap_next_ex(_device, &pkt_header, &pkt_data); + if (result == 1) { // Succeed + } + } + catch (invalid_argument& i) { + } + catch (out_of_range& o) { + }*/ + } + // Let's go + _running = TRUE; + while (_running) { // Loop while _running flag is up + if (_resume.try_lock() == TRUE) { // Previous packet was consumed, lock for the next one + write(_fd[1], "\n", 1); // Any character will do the job + } else { // not ready yet + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + } + + loggers::get_instance().log("<<< pcap_layer::run"); + return NULL; +} + +void pcap_layer::send_data(OCTETSTRING& data, params& params) { + loggers::get_instance().log_msg(">>> pcap_layer::send_data: ", data); + + if (_pcap_h != -1) { // Check if offline mode is used + if (pcap_sendpacket(_device, static_cast(data), data.lengthof()) == -1) { + loggers::get_instance().error("pcap_layer::send_data: Failed to send packet: %s", pcap_geterr(_device)); + } + } else if (_sent_file != NULL) { + struct pcap_pkthdr hdr; + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + std::chrono::milliseconds ms = std::chrono::duration_cast(now.time_since_epoch()); + hdr.ts.tv_sec = ms.count() / 1000; + hdr.ts.tv_usec = (ms.count() % 1000) * 1000; + hdr.caplen = data.lengthof(); + hdr.len = hdr.caplen; + pcap_dump((u_char *)_sent_file, &hdr, static_cast(data)); + } else { + loggers::get_instance().log("pcap_layer::send_data: Offline mode, operation was skipped"); + } +} + +void pcap_layer::receive_data(OCTETSTRING& data, params& params) { + loggers::get_instance().log(">>> pcap_layer::receive_data: Received %d bytes", data.lengthof()); + loggers::get_instance().log_to_hexa("Packet dump", data); + + // Pass the packet to the upper layers + receive_to_all_layers(data, params); +} + +void pcap_layer::Handle_Fd_Event_Readable(int fd) { + //loggers::get_instance().log(">>> pcap_layer::Handle_Fd_Event_Readable: %d", fd); + + pcap_o_pkthdr *pkt_header; + const u_char *pkt_data; + int result = pcap_next_ex(_device, (struct pcap_pkthdr**)&pkt_header, &pkt_data); + if (result == 1) { // Succeed + if (pkt_header->caplen > 14) { // Reject too small packet + //loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: %ld - % ld - %d", pkt_header->ts.tv_sec, pkt_header->ts.tv_usec, pkt_header->len); + // Fill parameters from PCAP layer + params params; + params.insert(std::pair(params::timestamp, std::to_string(pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)))); // Use milliseconds + // Process the packet at this layer + OCTETSTRING os(pkt_header->caplen, pkt_data); + //loggers::get_instance().log_to_hexa("pcap_layer::Handle_Fd_Event_Readable: ", os); + // TODO Case of caplen != len !!! + float duration; + loggers::get_instance().set_start_time(_time_key); + this->receive_data(os, params); // TODO Check execution time for decoding operation + loggers::get_instance().set_stop_time(_time_key, duration); + } + } // else, skip the packet + // Specific to offline mode + if (_fd[0] != -1) { // Check if offline mode is used + //loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: Read pipe"); + char c[2]; + read(_fd[0], &c, 1); + if (result == -2) { // End of file, therminate worker thread + _running = FALSE; + } + //loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: pcap_next_ex failed: result=%d", result); + _resume.unlock(); + } // else, nothing to do +} + +pcap_layer_factory pcap_layer_factory::_f; + +#endif // !CYGWIN diff --git a/ccsrc/Protocols/Pcap/pcap_layer.hh b/ccsrc/Protocols/Pcap/pcap_layer.hh index 098e1de3392a63c3e9e364a3e560dac519491dae..151eab8589372ef517b3ac979ce6cb0d89336c39 100644 --- a/ccsrc/Protocols/Pcap/pcap_layer.hh +++ b/ccsrc/Protocols/Pcap/pcap_layer.hh @@ -1,5 +1,5 @@ -#if defined (__CYGWIN__) - #include "pcap_cygwin_layer.hh" -#else - #include "pcap_linux_layer.hh" -#endif +#if defined (__CYGWIN__) + #include "pcap_cygwin_layer.hh" +#else + #include "pcap_linux_layer.hh" +#endif diff --git a/ccsrc/Protocols/Pcap/pcap_layer_factory.hh b/ccsrc/Protocols/Pcap/pcap_layer_factory.hh index e91d2eafebe7cf27db55a4b75c5126b72fde113a..0125e1946cb3359295bac349039fef518c70ce52 100644 --- a/ccsrc/Protocols/Pcap/pcap_layer_factory.hh +++ b/ccsrc/Protocols/Pcap/pcap_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file pcap_layer_factory.hh - * \brief Header file for Pcap layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "pcap_layer.hh" - -/*! - * \class pcap_layer_factory - * \brief This class provides a factory class to create an pcap_layer class instance - */ -class pcap_layer_factory : public layer_factory { - static pcap_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the udp_layer_factory class - * \remark The PCAP layer identifier is PCAP - */ - pcap_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("PCAP", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new pcap_layer(p_type, p_param); }; -}; // End of class pcap_layer_factory +/*! + * \file pcap_layer_factory.hh + * \brief Header file for Pcap layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "pcap_layer.hh" + +/*! + * \class pcap_layer_factory + * \brief This class provides a factory class to create an pcap_layer class instance + */ +class pcap_layer_factory : public layer_factory { + static pcap_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the udp_layer_factory class + * \remark The PCAP layer identifier is PCAP + */ + pcap_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("PCAP", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new pcap_layer(p_type, p_param); }; +}; // End of class pcap_layer_factory diff --git a/ccsrc/Protocols/Pcap/pcap_linux_layer.cc b/ccsrc/Protocols/Pcap/pcap_linux_layer.cc index b8a7e0486e21f8d1febe7baeee2c23cafdfcf6ff..531e15acff4ae5919771eba5d5bb8924251619ae 100644 --- a/ccsrc/Protocols/Pcap/pcap_linux_layer.cc +++ b/ccsrc/Protocols/Pcap/pcap_linux_layer.cc @@ -1,198 +1,198 @@ -#if !defined(__CYGWIN__) -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include "pcap_layer_factory.hh" - -#include "loggers.hh" - -static const char *_hexDigits = "0123456789ABCDEF"; -static char * _bin2hex(char *hex, size_t hlen, const char *bin, size_t blen) { - const unsigned char *b, *e; - char * s; - - // sanity check - if (hlen >= 0 && hlen < blen * 2) - return NULL; - - b = (const unsigned char *)bin; - e = b + blen - 1; - s = hex + blen * 2; - if (s < hex + hlen) - *s = 0; - for (; b <= e; e--) { - *(--s) = _hexDigits[(*e) & 0xF]; - *(--s) = _hexDigits[(*e) >> 4]; - } - return hex + blen * 2; -} - -pcap_layer::pcap_layer(const std::string &p_type, const std::string ¶m) - : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _pcap_h(-1), _time_key("pcap_layer::Handle_Fd_Event_Readable") { - char error_buffer[PCAP_ERRBUF_SIZE]; - params::const_iterator it; - std::string nic; - - loggers::get_instance().log(">>> pcap_layer::pcap_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - // Prepare capture processing - it = _params.find(params::nic); - if ((it == _params.end()) || it->second.empty()) { // Use online capture - loggers::get_instance().error("pcap_layer::pcap_layer: NIC name must be specified"); - return; - } - - nic = _params[params::nic]; - { - bpf_u_int32 net, mask; // ip address and subnet mask - if (pcap_lookupnet(nic.c_str(), &net, &mask, error_buffer) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to fetch newtork address for device %s", nic.c_str()); - } else { - loggers::get_instance().log("pcap_layer::pcap_layer: Device %s Network address: %d", nic.c_str(), net); - } - } - // Open the device in promiscuous mode - _device = pcap_open_live(nic.c_str(), 65536 /*64*1024*/, 1, 100, error_buffer); // TODO Replace hard coded values by pcap_layer:: - if (_device == NULL) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open device %s", nic.c_str()); - return; - } // else, continue - // Set non-blocking flag for the polling procedure - if (pcap_setnonblock(_device, 1, error_buffer) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set blocking mode: %s", error_buffer); - } - // Retrieve the device file handler - _pcap_h = pcap_get_selectable_fd(_device); - if (_pcap_h == -1) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to get device handler"); - } - - // Setup filter - std::string filter = ""; - std::string mac_src; - it = _params.find(params::mac_src); - if (it != _params.end()) { // Use online capture - mac_src = it->second; - } else { - // Detect MAC address of NIC - struct ifreq ifr; - memset(&ifr, 0, sizeof(ifr)); - nic.copy(ifr.ifr_name, sizeof(ifr.ifr_name)); - if (ioctl(_pcap_h, SIOCGIFHWADDR, &ifr) == -1) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to get device MAC address"); - } else { - char buf[13]; - *_bin2hex(buf, sizeof(buf), ifr.ifr_hwaddr.sa_data, 6) = 0; - mac_src = buf; - loggers::get_instance().user("pcap_layer::pcap_layer: local MAC is %s", mac_src.c_str()); - _params[params::mac_src] = mac_src; - } - } - - // Accept ITS broadcasted messages - std::string mac_bc; - it = _params.find(params::mac_bc); - if (it != _params.end() && !it->second.empty()) { - mac_bc = it->second; - } else { - mac_bc = "ffffffffffff"; - } - - if ((mac_bc == mac_src) || mac_src.empty()) { - filter = "ether dst " + mac_bc; - } else { - filter = "( ether dst " + mac_bc + " or ether dst " + mac_src + " )"; - } - - if (!mac_src.empty()) { - // Reject ITS messages sent by this component - filter += " and not ether src " + mac_src; - } - - // Add user defined filter - it = _params.find(std::string("filter")); - if ((it != _params.end()) && !it->second.empty()) { - filter += std::string(" ") + it->second; - } - // Log final PCAP filter - loggers::get_instance().user("pcap_layer::pcap_layer: Filter: %s", filter.c_str()); - - { - struct bpf_program f = {0}; - if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to compile PCAP filter"); - } else { - if (pcap_setfilter(_device, &f) != 0) { - loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set PCAP filter"); - } - } - pcap_freecode(&f); - } - - // Pass the device file handler to the polling procedure - Handler_Add_Fd_Read(_pcap_h); -} // End of ctor - -pcap_layer::~pcap_layer() { - loggers::get_instance().log(">>> pcap_layer::~pcap_layer"); - - if (_device != NULL) { - pcap_close(_device); - } -} // End of dtor - -void pcap_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> pcap_layer::send_data: ", data); - - if (pcap_sendpacket(_device, static_cast(data), data.lengthof()) == -1) { - loggers::get_instance().error("pcap_layer::send_data: Failed to send packet: %s", pcap_geterr(_device)); - } -} - -void pcap_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> pcap_layer::receive_data: Received %d bytes", data.lengthof()); - loggers::get_instance().log_to_hexa("Packet dump", data); - - // Pass the packet to the upper layers - receive_to_all_layers(data, params); -} - -void pcap_layer::Handle_Fd_Event_Readable(int fd) { - // loggers::get_instance().log(">>> pcap_layer::Handle_Fd_Event_Readable: %d", fd); - - pcap_pkthdr * pkt_header; - const u_char *pkt_data; - int result = pcap_next_ex(_device, &pkt_header, &pkt_data); - if (result == 1) { // Succeed - if (pkt_header->caplen > 14) { // Reject too small packet - loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: %ld - %ld - %ld - %d", pkt_header->ts.tv_sec, pkt_header->ts.tv_usec, - pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000), pkt_header->len); - // Fill parameters from PCAP layer - params params; - params.insert(std::pair( - params::timestamp, std::to_string(pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)))); // Use milliseconds - // Process the packet at this layer - OCTETSTRING os(pkt_header->caplen, pkt_data); - // loggers::get_instance().log_to_hexa("pcap_layer::Handle_Fd_Event_Readable: ", os); - // TODO Case of caplen != len !!! - float duration; - loggers::get_instance().set_start_time(_time_key); - this->receive_data(os, params); // TODO Check execution time for decoding operation - loggers::get_instance().set_stop_time(_time_key, duration); - } - } // else, skip the packet -} - -pcap_layer_factory pcap_layer_factory::_f; - -#endif // !CYGWIN +#if !defined(__CYGWIN__) +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "pcap_layer_factory.hh" + +#include "loggers.hh" + +static const char *_hexDigits = "0123456789ABCDEF"; +static char * _bin2hex(char *hex, size_t hlen, const char *bin, size_t blen) { + const unsigned char *b, *e; + char * s; + + // sanity check + if (hlen >= 0 && hlen < blen * 2) + return NULL; + + b = (const unsigned char *)bin; + e = b + blen - 1; + s = hex + blen * 2; + if (s < hex + hlen) + *s = 0; + for (; b <= e; e--) { + *(--s) = _hexDigits[(*e) & 0xF]; + *(--s) = _hexDigits[(*e) >> 4]; + } + return hex + blen * 2; +} + +pcap_layer::pcap_layer(const std::string &p_type, const std::string ¶m) + : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _pcap_h(-1), _time_key("pcap_layer::Handle_Fd_Event_Readable") { + char error_buffer[PCAP_ERRBUF_SIZE]; + params::const_iterator it; + std::string nic; + + loggers::get_instance().log(">>> pcap_layer::pcap_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + // Prepare capture processing + it = _params.find(params::nic); + if ((it == _params.end()) || it->second.empty()) { // Use online capture + loggers::get_instance().error("pcap_layer::pcap_layer: NIC name must be specified"); + return; + } + + nic = _params[params::nic]; + { + bpf_u_int32 net, mask; // ip address and subnet mask + if (pcap_lookupnet(nic.c_str(), &net, &mask, error_buffer) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to fetch newtork address for device %s", nic.c_str()); + } else { + loggers::get_instance().log("pcap_layer::pcap_layer: Device %s Network address: %d", nic.c_str(), net); + } + } + // Open the device in promiscuous mode + _device = pcap_open_live(nic.c_str(), 65536 /*64*1024*/, 1, 100, error_buffer); // TODO Replace hard coded values by pcap_layer:: + if (_device == NULL) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to open device %s", nic.c_str()); + return; + } // else, continue + // Set non-blocking flag for the polling procedure + if (pcap_setnonblock(_device, 1, error_buffer) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set blocking mode: %s", error_buffer); + } + // Retrieve the device file handler + _pcap_h = pcap_get_selectable_fd(_device); + if (_pcap_h == -1) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to get device handler"); + } + + // Setup filter + std::string filter = ""; + std::string mac_src; + it = _params.find(params::mac_src); + if (it != _params.end()) { // Use online capture + mac_src = it->second; + } else { + // Detect MAC address of NIC + struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); + nic.copy(ifr.ifr_name, sizeof(ifr.ifr_name)); + if (ioctl(_pcap_h, SIOCGIFHWADDR, &ifr) == -1) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to get device MAC address"); + } else { + char buf[13]; + *_bin2hex(buf, sizeof(buf), ifr.ifr_hwaddr.sa_data, 6) = 0; + mac_src = buf; + loggers::get_instance().user("pcap_layer::pcap_layer: local MAC is %s", mac_src.c_str()); + _params[params::mac_src] = mac_src; + } + } + + // Accept ITS broadcasted messages + std::string mac_bc; + it = _params.find(params::mac_bc); + if (it != _params.end() && !it->second.empty()) { + mac_bc = it->second; + } else { + mac_bc = "ffffffffffff"; + } + + if ((mac_bc == mac_src) || mac_src.empty()) { + filter = "ether dst " + mac_bc; + } else { + filter = "( ether dst " + mac_bc + " or ether dst " + mac_src + " )"; + } + + if (!mac_src.empty()) { + // Reject ITS messages sent by this component + filter += " and not ether src " + mac_src; + } + + // Add user defined filter + it = _params.find(std::string("filter")); + if ((it != _params.end()) && !it->second.empty()) { + filter += std::string(" ") + it->second; + } + // Log final PCAP filter + loggers::get_instance().user("pcap_layer::pcap_layer: Filter: %s", filter.c_str()); + + { + struct bpf_program f = {0}; + if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to compile PCAP filter"); + } else { + if (pcap_setfilter(_device, &f) != 0) { + loggers::get_instance().error("pcap_layer::pcap_layer: Failed to set PCAP filter"); + } + } + pcap_freecode(&f); + } + + // Pass the device file handler to the polling procedure + Handler_Add_Fd_Read(_pcap_h); +} // End of ctor + +pcap_layer::~pcap_layer() { + loggers::get_instance().log(">>> pcap_layer::~pcap_layer"); + + if (_device != NULL) { + pcap_close(_device); + } +} // End of dtor + +void pcap_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> pcap_layer::send_data: ", data); + + if (pcap_sendpacket(_device, static_cast(data), data.lengthof()) == -1) { + loggers::get_instance().error("pcap_layer::send_data: Failed to send packet: %s", pcap_geterr(_device)); + } +} + +void pcap_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> pcap_layer::receive_data: Received %d bytes", data.lengthof()); + loggers::get_instance().log_to_hexa("Packet dump", data); + + // Pass the packet to the upper layers + receive_to_all_layers(data, params); +} + +void pcap_layer::Handle_Fd_Event_Readable(int fd) { + // loggers::get_instance().log(">>> pcap_layer::Handle_Fd_Event_Readable: %d", fd); + + pcap_pkthdr * pkt_header; + const u_char *pkt_data; + int result = pcap_next_ex(_device, &pkt_header, &pkt_data); + if (result == 1) { // Succeed + if (pkt_header->caplen > 14) { // Reject too small packet + loggers::get_instance().log("pcap_layer::Handle_Fd_Event_Readable: %ld - %ld - %ld - %d", pkt_header->ts.tv_sec, pkt_header->ts.tv_usec, + pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000), pkt_header->len); + // Fill parameters from PCAP layer + params params; + params.insert(std::pair( + params::timestamp, std::to_string(pkt_header->ts.tv_sec * 1000 + static_cast(pkt_header->ts.tv_usec / 1000)))); // Use milliseconds + // Process the packet at this layer + OCTETSTRING os(pkt_header->caplen, pkt_data); + // loggers::get_instance().log_to_hexa("pcap_layer::Handle_Fd_Event_Readable: ", os); + // TODO Case of caplen != len !!! + float duration; + loggers::get_instance().set_start_time(_time_key); + this->receive_data(os, params); // TODO Check execution time for decoding operation + loggers::get_instance().set_stop_time(_time_key, duration); + } + } // else, skip the packet +} + +pcap_layer_factory pcap_layer_factory::_f; + +#endif // !CYGWIN diff --git a/ccsrc/Protocols/Pcap/pcap_linux_layer.hh b/ccsrc/Protocols/Pcap/pcap_linux_layer.hh index 447c0d6bc4f01da7dec16fbd4357d2cc14536869..82efc4b5857fd29cb944cdbcc775f98719ec3570 100644 --- a/ccsrc/Protocols/Pcap/pcap_linux_layer.hh +++ b/ccsrc/Protocols/Pcap/pcap_linux_layer.hh @@ -1,62 +1,62 @@ -/*! - * \file pcap_layer.hh - * \brief Header file for ITS Pcap port layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "params.hh" -#include "t_layer.hh" - -class PORT; //! Forward declaration of TITAN class - -/*! - * \class pcap_layer - * \brief This class provides description of ITS PCAP port protocol layer - */ -class pcap_layer : public layer, public PORT { - params _params; //! Layer parameters - pcap_t * _device; //! Device handle - int _pcap_h; //! PCAP instance handle - pcap_dumper_t *_sent_file; //! Write file handle to save sent packet, used in file mode - std::string _time_key; //! \todo - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the pcap_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - pcap_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~pcap_layer(); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - void Handle_Fd_Event_Readable(int fd); -}; +/*! + * \file pcap_layer.hh + * \brief Header file for ITS Pcap port layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "params.hh" +#include "t_layer.hh" + +class PORT; //! Forward declaration of TITAN class + +/*! + * \class pcap_layer + * \brief This class provides description of ITS PCAP port protocol layer + */ +class pcap_layer : public layer, public PORT { + params _params; //! Layer parameters + pcap_t * _device; //! Device handle + int _pcap_h; //! PCAP instance handle + pcap_dumper_t *_sent_file; //! Write file handle to save sent packet, used in file mode + std::string _time_key; //! \todo + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the pcap_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + pcap_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~pcap_layer(); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + void Handle_Fd_Event_Readable(int fd); +}; diff --git a/ccsrc/Protocols/Pcap/pcap_offline_layer.cc b/ccsrc/Protocols/Pcap/pcap_offline_layer.cc index fd4c82f31e79530784cb536696f333bf8c2761b8..6699ad63c56c36dc0c4e4970a76ebd6b9b331b9f 100644 --- a/ccsrc/Protocols/Pcap/pcap_offline_layer.cc +++ b/ccsrc/Protocols/Pcap/pcap_offline_layer.cc @@ -1,227 +1,227 @@ -#if defined(__CYGWIN__) -#define _GNU_SOURCE -#endif -#include -#include -#include -#include -#include - -#include - -#include "pcap_offline_layer_factory.hh" - -#include "loggers.hh" - -#include - -#ifdef __CYGWIN__ -typedef struct { - bpf_int32 tv_sec; /* seconds */ - bpf_int32 tv_usec; /* microseconds */ -} pcap_o_timeval; - -typedef struct pcap_o_pkthdr { - pcap_o_timeval ts; /* time stamp */ - bpf_u_int32 caplen; /* length of portion present */ - bpf_u_int32 len; /* length this packet (off wire) */ -} pcap_o_pkthdr; -#else -typedef struct pcap_pkthdr pcap_o_pkthdr; -typedef struct timeval pcap_o_timeval; -#endif - -pcap_offline_layer::pcap_offline_layer(const std::string &p_type, const std::string ¶m) - : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _running(FALSE), _time_key("pcap_offline_layer::Handle_Fd_Event_Readable") { - loggers::get_instance().log(">>> pcap_offline_layer::pcap_offline_layer: %s, %s", p_type.c_str(), param.c_str()); - params::convert(_params, param); - - _o_params.insert(std::pair(std::string("timestamp"), std::string())); - - char error_buffer[PCAP_ERRBUF_SIZE]; - params::const_iterator it; - - it = _params.find(std::string("realtime")); - _realtime = ((it != _params.end()) && !it->second.empty()); - - it = _params.find(std::string("loop")); - _loop = ((it != _params.end()) && !it->second.empty()); - - it = _params.find(std::string("file")); - if ((it != _params.end()) && !it->second.empty()) { - const std::string &file = it->second; - _device = pcap_open_offline(file.c_str(), error_buffer); - if (_device) { - - // Add user defined filter - it = _params.find(std::string("filter")); - if ((it != _params.end()) && !it->second.empty()) { - const std::string &filter = it->second; - // Log final PCAP filter - loggers::get_instance().user("pcap_offline_layer::pcap_offline_layer: Filter: %s", filter.c_str()); - struct bpf_program f = {0}; - if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { - loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to compile PCAP filter"); - } else { - if (pcap_setfilter(_device, &f) != 0) { - loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to set PCAP filter"); - } - } - pcap_freecode(&f); - } - - // create pipe and run thread - if (pipe2(_fd, O_NONBLOCK) == -1) { - loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to create a pipe: %s", ::strerror(errno)); - } - // Pass the pipe handler to the polling procedure - loggers::get_instance().log("pcap_offline_layer::pcap_offline_layer: Call handler with descriptor %d", _fd[0]); - Handler_Add_Fd_Read(_fd[0]); - // Create the offline reader thread - _thread = new std::thread(&pcap_offline_layer::run, (void *)this); - if (_thread == NULL) { - loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to start offline thread"); - } - while (_running == FALSE) { - std::this_thread::sleep_for(std::chrono::milliseconds(500)); - } - // Thread was started - loggers::get_instance().log("<<< pcap_offline_layer::pcap_offline_layer"); - } - } -} // End of ctor - -pcap_offline_layer::~pcap_offline_layer() { - loggers::get_instance().log(">>> pcap_offline_layer::~pcap_offline_layer"); - - if (_device != NULL) { - if (_thread != NULL) { - _running = FALSE; - // Wait for the working thread to terminate - _thread->join(); - loggers::get_instance().log("pcap_offline_layer::~pcap_offline_layer: Thread were stops"); - // Cleanup - delete _thread; - close(_fd[0]); - close(_fd[1]); - } - pcap_close(_device); - } -} // End of dtor - -void *pcap_offline_layer::run(void *p_this) { - pcap_offline_layer &p = *static_cast(p_this); - return p.thread(); -} - -static long timeval_diff(const pcap_o_timeval &x, const pcap_o_timeval &y) { - pcap_o_timeval z = y; - /* Perform the carry for the later subtraction by updating y. */ - if (x.tv_usec < y.tv_usec) { - int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1; - z.tv_usec -= 1000000 * nsec; - z.tv_sec += nsec; - } - if (x.tv_usec - z.tv_usec > 1000000) { - int nsec = (x.tv_usec - z.tv_usec) / 1000000; - z.tv_usec += 1000000 * nsec; - z.tv_sec -= nsec; - } - - return (x.tv_sec - z.tv_sec) * 1000 + ((x.tv_usec - z.tv_usec) / 1000); -} - -void *pcap_offline_layer::thread() { - pcap_o_pkthdr *pkt_header; - pcap_o_pkthdr lh; - const u_char * pkt_data; - unsigned char pkt_count = 0; - - // loggers::get_instance().log(">>> pcap_offline_layer::run"); - - memset(&lh, 0, sizeof(lh)); - - _running = TRUE; - - int delay = 1000; - params::const_iterator it; - it = _params.find(std::string("delay")); - if (it != _params.cend()) { - delay = std::stoi(it->second); - } - - // wait a bit before sending first packet - std::this_thread::sleep_for(std::chrono::milliseconds(delay)); - - while (_running) { // Loop while _running flag is up - // get next frame - int result = pcap_next_ex(_device, (struct pcap_pkthdr **)&pkt_header, &pkt_data); - if (result == 2) { - if (_loop) { - - } else { - _running = FALSE; - return NULL; - } - } - if (_realtime) { - // wait for next packet timestamp - if (lh.ts.tv_sec | lh.ts.tv_usec) { - long diff = timeval_diff(pkt_header->ts, lh.ts); - if (diff > 0) { - loggers::get_instance().log("<<< pcap_offline_layer::run: Wait %d msec", diff); - std::this_thread::sleep_for(std::chrono::milliseconds(diff)); - loggers::get_instance().log("<<< pcap_offline_layer::run: Wait done"); - } - } - } - while (_running && !_resume.try_lock()) { - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - } - lh = *pkt_header; -#if 0 - { - char buf[128]; - std::time_t t = pkt_header->ts.tv_sec; - std::tm * pt = std::localtime( &t ); - t = std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", pt); - std::sprintf(buf+t, ".%06ld", pkt_header->ts.tv_usec); - _o_params["timestamp"] = std::string(buf); - } -#else - _o_params["timestamp"] = std::to_string(pkt_header->ts.tv_usec); -#endif - _o_data = OCTETSTRING(pkt_header->len, pkt_data); - write(_fd[1], &pkt_count, 1); - pkt_count++; - } - - // loggers::get_instance().log("<<< pcap_offline_layer::run"); - return NULL; -} - -void pcap_offline_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log("pcap_offline_layer::send_data: Offline mode, operation was skipped"); -} - -void pcap_offline_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log(">>> pcap_offline_layer::receive_data: Received %d bytes", data.lengthof()); - loggers::get_instance().log_to_hexa("Packet dump", data); - - // Pass the packet to the upper layers - receive_to_all_layers(data, params); -} - -void pcap_offline_layer::Handle_Fd_Event_Readable(int fd) { - // loggers::get_instance().log(">>> pcap_offline_layer::Handle_Fd_Event_Readable: %d", fd); - char c[2]; - float duration; - // Process the packet at this layer - loggers::get_instance().set_start_time(_time_key); - this->receive_data(_o_data, _o_params); - loggers::get_instance().set_stop_time(_time_key, duration); - read(_fd[0], &c, 1); - _resume.unlock(); -} - -pcap_offline_layer_factory pcap_offline_layer_factory::_f; +#if defined(__CYGWIN__) +#define _GNU_SOURCE +#endif +#include +#include +#include +#include +#include + +#include + +#include "pcap_offline_layer_factory.hh" + +#include "loggers.hh" + +#include + +#ifdef __CYGWIN__ +typedef struct { + bpf_int32 tv_sec; /* seconds */ + bpf_int32 tv_usec; /* microseconds */ +} pcap_o_timeval; + +typedef struct pcap_o_pkthdr { + pcap_o_timeval ts; /* time stamp */ + bpf_u_int32 caplen; /* length of portion present */ + bpf_u_int32 len; /* length this packet (off wire) */ +} pcap_o_pkthdr; +#else +typedef struct pcap_pkthdr pcap_o_pkthdr; +typedef struct timeval pcap_o_timeval; +#endif + +pcap_offline_layer::pcap_offline_layer(const std::string &p_type, const std::string ¶m) + : layer(p_type), PORT(p_type.c_str()), _params(), _device(NULL), _running(FALSE), _time_key("pcap_offline_layer::Handle_Fd_Event_Readable") { + loggers::get_instance().log(">>> pcap_offline_layer::pcap_offline_layer: %s, %s", p_type.c_str(), param.c_str()); + params::convert(_params, param); + + _o_params.insert(std::pair(std::string("timestamp"), std::string())); + + char error_buffer[PCAP_ERRBUF_SIZE]; + params::const_iterator it; + + it = _params.find(std::string("realtime")); + _realtime = ((it != _params.end()) && !it->second.empty()); + + it = _params.find(std::string("loop")); + _loop = ((it != _params.end()) && !it->second.empty()); + + it = _params.find(std::string("file")); + if ((it != _params.end()) && !it->second.empty()) { + const std::string &file = it->second; + _device = pcap_open_offline(file.c_str(), error_buffer); + if (_device) { + + // Add user defined filter + it = _params.find(std::string("filter")); + if ((it != _params.end()) && !it->second.empty()) { + const std::string &filter = it->second; + // Log final PCAP filter + loggers::get_instance().user("pcap_offline_layer::pcap_offline_layer: Filter: %s", filter.c_str()); + struct bpf_program f = {0}; + if (pcap_compile(_device, &f, filter.c_str(), 1, PCAP_NETMASK_UNKNOWN) != 0) { + loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to compile PCAP filter"); + } else { + if (pcap_setfilter(_device, &f) != 0) { + loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to set PCAP filter"); + } + } + pcap_freecode(&f); + } + + // create pipe and run thread + if (pipe2(_fd, O_NONBLOCK) == -1) { + loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to create a pipe: %s", ::strerror(errno)); + } + // Pass the pipe handler to the polling procedure + loggers::get_instance().log("pcap_offline_layer::pcap_offline_layer: Call handler with descriptor %d", _fd[0]); + Handler_Add_Fd_Read(_fd[0]); + // Create the offline reader thread + _thread = new std::thread(&pcap_offline_layer::run, (void *)this); + if (_thread == NULL) { + loggers::get_instance().error("pcap_offline_layer::pcap_offline_layer: Failed to start offline thread"); + } + while (_running == FALSE) { + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + } + // Thread was started + loggers::get_instance().log("<<< pcap_offline_layer::pcap_offline_layer"); + } + } +} // End of ctor + +pcap_offline_layer::~pcap_offline_layer() { + loggers::get_instance().log(">>> pcap_offline_layer::~pcap_offline_layer"); + + if (_device != NULL) { + if (_thread != NULL) { + _running = FALSE; + // Wait for the working thread to terminate + _thread->join(); + loggers::get_instance().log("pcap_offline_layer::~pcap_offline_layer: Thread were stops"); + // Cleanup + delete _thread; + close(_fd[0]); + close(_fd[1]); + } + pcap_close(_device); + } +} // End of dtor + +void *pcap_offline_layer::run(void *p_this) { + pcap_offline_layer &p = *static_cast(p_this); + return p.thread(); +} + +static long timeval_diff(const pcap_o_timeval &x, const pcap_o_timeval &y) { + pcap_o_timeval z = y; + /* Perform the carry for the later subtraction by updating y. */ + if (x.tv_usec < y.tv_usec) { + int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1; + z.tv_usec -= 1000000 * nsec; + z.tv_sec += nsec; + } + if (x.tv_usec - z.tv_usec > 1000000) { + int nsec = (x.tv_usec - z.tv_usec) / 1000000; + z.tv_usec += 1000000 * nsec; + z.tv_sec -= nsec; + } + + return (x.tv_sec - z.tv_sec) * 1000 + ((x.tv_usec - z.tv_usec) / 1000); +} + +void *pcap_offline_layer::thread() { + pcap_o_pkthdr *pkt_header; + pcap_o_pkthdr lh; + const u_char * pkt_data; + unsigned char pkt_count = 0; + + // loggers::get_instance().log(">>> pcap_offline_layer::run"); + + memset(&lh, 0, sizeof(lh)); + + _running = TRUE; + + int delay = 1000; + params::const_iterator it; + it = _params.find(std::string("delay")); + if (it != _params.cend()) { + delay = std::stoi(it->second); + } + + // wait a bit before sending first packet + std::this_thread::sleep_for(std::chrono::milliseconds(delay)); + + while (_running) { // Loop while _running flag is up + // get next frame + int result = pcap_next_ex(_device, (struct pcap_pkthdr **)&pkt_header, &pkt_data); + if (result == 2) { + if (_loop) { + + } else { + _running = FALSE; + return NULL; + } + } + if (_realtime) { + // wait for next packet timestamp + if (lh.ts.tv_sec | lh.ts.tv_usec) { + long diff = timeval_diff(pkt_header->ts, lh.ts); + if (diff > 0) { + loggers::get_instance().log("<<< pcap_offline_layer::run: Wait %d msec", diff); + std::this_thread::sleep_for(std::chrono::milliseconds(diff)); + loggers::get_instance().log("<<< pcap_offline_layer::run: Wait done"); + } + } + } + while (_running && !_resume.try_lock()) { + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } + lh = *pkt_header; +#if 0 + { + char buf[128]; + std::time_t t = pkt_header->ts.tv_sec; + std::tm * pt = std::localtime( &t ); + t = std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", pt); + std::sprintf(buf+t, ".%06ld", pkt_header->ts.tv_usec); + _o_params["timestamp"] = std::string(buf); + } +#else + _o_params["timestamp"] = std::to_string(pkt_header->ts.tv_usec); +#endif + _o_data = OCTETSTRING(pkt_header->len, pkt_data); + write(_fd[1], &pkt_count, 1); + pkt_count++; + } + + // loggers::get_instance().log("<<< pcap_offline_layer::run"); + return NULL; +} + +void pcap_offline_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log("pcap_offline_layer::send_data: Offline mode, operation was skipped"); +} + +void pcap_offline_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log(">>> pcap_offline_layer::receive_data: Received %d bytes", data.lengthof()); + loggers::get_instance().log_to_hexa("Packet dump", data); + + // Pass the packet to the upper layers + receive_to_all_layers(data, params); +} + +void pcap_offline_layer::Handle_Fd_Event_Readable(int fd) { + // loggers::get_instance().log(">>> pcap_offline_layer::Handle_Fd_Event_Readable: %d", fd); + char c[2]; + float duration; + // Process the packet at this layer + loggers::get_instance().set_start_time(_time_key); + this->receive_data(_o_data, _o_params); + loggers::get_instance().set_stop_time(_time_key, duration); + read(_fd[0], &c, 1); + _resume.unlock(); +} + +pcap_offline_layer_factory pcap_offline_layer_factory::_f; diff --git a/ccsrc/Protocols/Pcap/pcap_offline_layer.hh b/ccsrc/Protocols/Pcap/pcap_offline_layer.hh index a58e89a0ae5a510ca112608c32a01aaf9cd7a528..0c1993e4118aef4c6977bcde7896f2d1efdfaa63 100644 --- a/ccsrc/Protocols/Pcap/pcap_offline_layer.hh +++ b/ccsrc/Protocols/Pcap/pcap_offline_layer.hh @@ -1,80 +1,80 @@ -/*! - * \file pcap_offline_layer.hh - * \brief Header file for ITS Offline Pcap port layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include - -#include "params.hh" -#include "t_layer.hh" - -#include - -class PORT; //! Forward declaration of TITAN class - -typedef struct pcap pcap_t; - -/*! - * \class pcap_layer - * \brief This class provides description of ITS PCAP port protocol layer - */ -class pcap_offline_layer : public layer, public PORT { - params _params; //! Layer parameters - pcap_t * _device; //! Device handle - std::thread *_thread; //! Thread handle, used to read PCAP file instead of NIC, used in file mode - std::mutex _resume; - bool _running; //! Set to true when the thread is running, used in file mode - bool _realtime; //! Set to true if realtime delay shall be added between packets - bool _loop; //! Set to true if playback shall be looped - int _fd[2]; //! pipe to signal to Titan - - params _o_params; - OCTETSTRING _o_data; - - std::string _time_key; - - static void *run(void *p_this); - -public: - void *thread(void); - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the pcap_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - pcap_offline_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - */ - virtual ~pcap_offline_layer(); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - void Handle_Fd_Event_Readable(int fd); -}; +/*! + * \file pcap_offline_layer.hh + * \brief Header file for ITS Offline Pcap port layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include + +#include "params.hh" +#include "t_layer.hh" + +#include + +class PORT; //! Forward declaration of TITAN class + +typedef struct pcap pcap_t; + +/*! + * \class pcap_layer + * \brief This class provides description of ITS PCAP port protocol layer + */ +class pcap_offline_layer : public layer, public PORT { + params _params; //! Layer parameters + pcap_t * _device; //! Device handle + std::thread *_thread; //! Thread handle, used to read PCAP file instead of NIC, used in file mode + std::mutex _resume; + bool _running; //! Set to true when the thread is running, used in file mode + bool _realtime; //! Set to true if realtime delay shall be added between packets + bool _loop; //! Set to true if playback shall be looped + int _fd[2]; //! pipe to signal to Titan + + params _o_params; + OCTETSTRING _o_data; + + std::string _time_key; + + static void *run(void *p_this); + +public: + void *thread(void); + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the pcap_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + pcap_offline_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + */ + virtual ~pcap_offline_layer(); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + void Handle_Fd_Event_Readable(int fd); +}; diff --git a/ccsrc/Protocols/Pcap/pcap_offline_layer_factory.hh b/ccsrc/Protocols/Pcap/pcap_offline_layer_factory.hh index e6126bb300982f4399ebe369e8a50aaef5c61d86..23cd1d0d28f84386a20a1bdb2b35a0716f010fc9 100644 --- a/ccsrc/Protocols/Pcap/pcap_offline_layer_factory.hh +++ b/ccsrc/Protocols/Pcap/pcap_offline_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file pcap_offline_layer_factory.hh - * \brief Header file for Pcap layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "pcap_offline_layer.hh" - -/*! - * \class pcap_offline_layer_factory - * \brief This class provides a factory class to create an pcap_offline_layer class instance - */ -class pcap_offline_layer_factory : public layer_factory { - static pcap_offline_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the udp_layer_factory class - * \remark The PCAP layer identifier is PCAP - */ - pcap_offline_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("PCAP_FILE", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new pcap_offline_layer(p_type, p_param); }; -}; // End of class pcap_offline_layer_factory +/*! + * \file pcap_offline_layer_factory.hh + * \brief Header file for Pcap layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "pcap_offline_layer.hh" + +/*! + * \class pcap_offline_layer_factory + * \brief This class provides a factory class to create an pcap_offline_layer class instance + */ +class pcap_offline_layer_factory : public layer_factory { + static pcap_offline_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the udp_layer_factory class + * \remark The PCAP layer identifier is PCAP + */ + pcap_offline_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("PCAP_FILE", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new pcap_offline_layer(p_type, p_param); }; +}; // End of class pcap_offline_layer_factory diff --git a/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.cc b/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.cc index e597e329b8f28a1671a50593e0e72e470dc5a2fd..1a9819e0d2c2972fb2baed31f0ac9747eaccf36e 100644 --- a/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.cc +++ b/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.cc @@ -1,29 +1,29 @@ -#include "etsi_ts102941_trust_lists_ctl_format.hh" - -#include "loggers.hh" - -int etsi_ts102941_trust_lists_ctl_format::encode(const EtsiTs102941TrustLists::CtlFormat &p_ctl_format, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_trust_lists_ctl_format::encode: %s", p_ctl_format.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_ctl_format.encode(*p_ctl_format.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_trust_lists_ctl_format::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_trust_lists_ctl_format::decode(const OCTETSTRING &p_data, EtsiTs102941TrustLists::CtlFormat &p_ctl_format, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_trust_lists_ctl_format::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_ctl_format.decode(*p_ctl_format.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_trust_lists_ctl_format::decode: ", (const Base_Type &)p_ctl_format); - return 0; -} +#include "etsi_ts102941_trust_lists_ctl_format.hh" + +#include "loggers.hh" + +int etsi_ts102941_trust_lists_ctl_format::encode(const EtsiTs102941TrustLists::CtlFormat &p_ctl_format, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_trust_lists_ctl_format::encode: %s", p_ctl_format.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_ctl_format.encode(*p_ctl_format.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_trust_lists_ctl_format::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_trust_lists_ctl_format::decode(const OCTETSTRING &p_data, EtsiTs102941TrustLists::CtlFormat &p_ctl_format, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_trust_lists_ctl_format::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_ctl_format.decode(*p_ctl_format.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_trust_lists_ctl_format::decode: ", (const Base_Type &)p_ctl_format); + return 0; +} diff --git a/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.hh b/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.hh index 84c928891dbc6b217c9b9f08706be872eedb779a..bce246eaa59371277db0a6ea02a1d2265a378bae 100644 --- a/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.hh +++ b/ccsrc/Protocols/Pki/etsi_ts102941_trust_lists_ctl_format.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TrustLists.hh" - -class etsi_ts102941_trust_lists_ctl_format : public codec { -public: - explicit etsi_ts102941_trust_lists_ctl_format() : codec(){}; - virtual ~etsi_ts102941_trust_lists_ctl_format(){}; - - virtual int encode(const EtsiTs102941TrustLists::CtlFormat &p_ctl_format, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TrustLists::CtlFormat &p_ctl_format, params *p_params = NULL); -}; // End of class etsi_ts102941_trust_lists_ctl_format +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TrustLists.hh" + +class etsi_ts102941_trust_lists_ctl_format : public codec { +public: + explicit etsi_ts102941_trust_lists_ctl_format() : codec(){}; + virtual ~etsi_ts102941_trust_lists_ctl_format(){}; + + virtual int encode(const EtsiTs102941TrustLists::CtlFormat &p_ctl_format, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TrustLists::CtlFormat &p_ctl_format, params *p_params = NULL); +}; // End of class etsi_ts102941_trust_lists_ctl_format diff --git a/ccsrc/Protocols/Pki/module.mk b/ccsrc/Protocols/Pki/module.mk index a6d0d34688af51f701197290f96132840b6b5628..6cfe387ce1d0b788baad85377a9a01c7dbd3544f 100644 --- a/ccsrc/Protocols/Pki/module.mk +++ b/ccsrc/Protocols/Pki/module.mk @@ -1,2 +1,2 @@ -sources := etsi_ts102941_trust_lists_ctl_format.cc -includes := . +sources := etsi_ts102941_trust_lists_ctl_format.cc +includes := . diff --git a/ccsrc/Protocols/Qualcomm/module.mk b/ccsrc/Protocols/Qualcomm/module.mk index c2fcfbe7067c92e20f91026156e51358dabd1555..18ae43f820efe775cbc4405304df43681db3dc2f 100644 --- a/ccsrc/Protocols/Qualcomm/module.mk +++ b/ccsrc/Protocols/Qualcomm/module.mk @@ -1,3 +1,3 @@ -sources := qualcomm_layer.cc -includes := . - +sources := qualcomm_layer.cc +includes := . + diff --git a/ccsrc/Protocols/Qualcomm/qualcomm_layer.cc b/ccsrc/Protocols/Qualcomm/qualcomm_layer.cc index 1492b336d82e6d71c97bfa6c18c0d66fe453f838..930f331f2ac203993d558198d0bdf3259ce6620b 100644 --- a/ccsrc/Protocols/Qualcomm/qualcomm_layer.cc +++ b/ccsrc/Protocols/Qualcomm/qualcomm_layer.cc @@ -1,39 +1,39 @@ -#include -#include -#include - -#include "qualcomm_layer_factory.hh" - -#include "loggers.hh" - -#include "converter.hh" - -qualcomm_layer::qualcomm_layer(const std::string &p_type, const std::string ¶m) : layer(p_type), _params() { - loggers::get_instance().log(">>> qualcomm_layer::qualcomm_layer: %s, %s", to_string().c_str(), param.c_str()); - - // Setup parameters - params::convert(_params, param); - //_params.log(); -} - -void qualcomm_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> qualcomm_layer::send_data: ", data); - - OCTETSTRING buffer = int2oct(3, 1); // CV2X identifier - buffer += data; // Payload - - loggers::get_instance().log_msg("qualcomm_layer::send_data: Final buffer=", buffer); - send_to_all_layers(buffer, params); -} - -void qualcomm_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> qualcomm_layer::receive_data: ", data); - - // Remove CV2X identifier - data = OCTETSTRING(data.lengthof() - 1, 1 + static_cast(data)); - loggers::get_instance().log_msg("qualcomm_layer::receive_data: payload for upper layer:", data); - - // FIXME receive_to_all_layers(data, params); -} - -qualcomm_layer_factory qualcomm_layer_factory::_f; +#include +#include +#include + +#include "qualcomm_layer_factory.hh" + +#include "loggers.hh" + +#include "converter.hh" + +qualcomm_layer::qualcomm_layer(const std::string &p_type, const std::string ¶m) : layer(p_type), _params() { + loggers::get_instance().log(">>> qualcomm_layer::qualcomm_layer: %s, %s", to_string().c_str(), param.c_str()); + + // Setup parameters + params::convert(_params, param); + //_params.log(); +} + +void qualcomm_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> qualcomm_layer::send_data: ", data); + + OCTETSTRING buffer = int2oct(3, 1); // CV2X identifier + buffer += data; // Payload + + loggers::get_instance().log_msg("qualcomm_layer::send_data: Final buffer=", buffer); + send_to_all_layers(buffer, params); +} + +void qualcomm_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> qualcomm_layer::receive_data: ", data); + + // Remove CV2X identifier + data = OCTETSTRING(data.lengthof() - 1, 1 + static_cast(data)); + loggers::get_instance().log_msg("qualcomm_layer::receive_data: payload for upper layer:", data); + + // FIXME receive_to_all_layers(data, params); +} + +qualcomm_layer_factory qualcomm_layer_factory::_f; diff --git a/ccsrc/Protocols/Qualcomm/qualcomm_layer.hh b/ccsrc/Protocols/Qualcomm/qualcomm_layer.hh index 1f97cb0a904a38a1337872d7298f1fcde9ee9d7d..cb83be06547e8600a5da0d11b3158ad2afd349de 100644 --- a/ccsrc/Protocols/Qualcomm/qualcomm_layer.hh +++ b/ccsrc/Protocols/Qualcomm/qualcomm_layer.hh @@ -1,43 +1,43 @@ -/*! - * \file udp_layer_factory.hh - * \brief Header file for ITS Qualcomm port protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "params.hh" -#include "t_layer.hh" - -class OCTETSTRING; //! Forward declaration of TITAN class - -/*! - * \class qualcomm_layer - * \brief This class provides description of ITS Qualcomm port protocol layer - */ -class qualcomm_layer : public layer { - - params _params; //! Layer parameters - -public: - //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the qualcomm_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - qualcomm_layer(const std::string &p_type, const std::string ¶m); - /*! - * \brief Default destructor - * \remark If \see _reconnect_on_send is set to false, the disconnection is done by the destructor - */ - virtual ~qualcomm_layer(){}; - - virtual void send_data(OCTETSTRING &data, params ¶ms); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class qualcomm_layer +/*! + * \file udp_layer_factory.hh + * \brief Header file for ITS Qualcomm port protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "params.hh" +#include "t_layer.hh" + +class OCTETSTRING; //! Forward declaration of TITAN class + +/*! + * \class qualcomm_layer + * \brief This class provides description of ITS Qualcomm port protocol layer + */ +class qualcomm_layer : public layer { + + params _params; //! Layer parameters + +public: + //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the qualcomm_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + qualcomm_layer(const std::string &p_type, const std::string ¶m); + /*! + * \brief Default destructor + * \remark If \see _reconnect_on_send is set to false, the disconnection is done by the destructor + */ + virtual ~qualcomm_layer(){}; + + virtual void send_data(OCTETSTRING &data, params ¶ms); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class qualcomm_layer diff --git a/ccsrc/Protocols/Qualcomm/qualcomm_layer_factory.hh b/ccsrc/Protocols/Qualcomm/qualcomm_layer_factory.hh index f85bcac0d72cbf4f7ce002a3145cbc095ffc705f..0d50c26cefd4a422de8f24907650d3652e0dd67f 100644 --- a/ccsrc/Protocols/Qualcomm/qualcomm_layer_factory.hh +++ b/ccsrc/Protocols/Qualcomm/qualcomm_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file qualcomm_layer_factory.hh - * \brief Header file for ITS Qualcomm protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "qualcomm_layer.hh" - -/*! - * \class qualcomm_layer_factory - * \brief This class provides a factory class to create an qualcomm_layer class instance - */ -class qualcomm_layer_factory : public layer_factory { - static qualcomm_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the udp_layer_factory class - * \remark The Qualcomm layer identifier is QUALCOMM - */ - qualcomm_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("QUALCOMM", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new qualcomm_layer(p_type, p_param); }; -}; // End of class qualcomm_layer_factory +/*! + * \file qualcomm_layer_factory.hh + * \brief Header file for ITS Qualcomm protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "qualcomm_layer.hh" + +/*! + * \class qualcomm_layer_factory + * \brief This class provides a factory class to create an qualcomm_layer class instance + */ +class qualcomm_layer_factory : public layer_factory { + static qualcomm_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the udp_layer_factory class + * \remark The Qualcomm layer identifier is QUALCOMM + */ + qualcomm_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("QUALCOMM", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new qualcomm_layer(p_type, p_param); }; +}; // End of class qualcomm_layer_factory diff --git a/ccsrc/Protocols/RawSocket/module.mk b/ccsrc/Protocols/RawSocket/module.mk index b8dee6571bcf786732058c20585f5580807fab65..ac33f1645b9054188eca388106e3abe63715d0f3 100644 --- a/ccsrc/Protocols/RawSocket/module.mk +++ b/ccsrc/Protocols/RawSocket/module.mk @@ -1,3 +1,3 @@ -sources := raw_socket_layer.cc -includes := . - +sources := raw_socket_layer.cc +includes := . + diff --git a/ccsrc/Protocols/Rtcmem/RtcmemCodec.cc b/ccsrc/Protocols/Rtcmem/RtcmemCodec.cc index 5d652ac7cd7afe7b78ebb18ddba6fa97250e39fd..416879d2a30990e9b57136b69f1f12783be481a2 100644 --- a/ccsrc/Protocols/Rtcmem/RtcmemCodec.cc +++ b/ccsrc/Protocols/Rtcmem/RtcmemCodec.cc @@ -1,39 +1,39 @@ -#include "RtcmemCodec.hh" -#include "LibItsRtcmem_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int RtcmemCodec::encode(const RTCMEM__PDU__Descriptions::RTCMEM &rtcmem, OCTETSTRING &data) { - loggers::get_instance().log(">>> RtcmemCodec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(rtcmem, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("RtcmemCodec::encode: ", data); - } - return rc; -} - -int RtcmemCodec::decode(const OCTETSTRING &data, RTCMEM__PDU__Descriptions::RTCMEM &p_rtcmem, params *params) { - loggers::get_instance().log_msg(">>> RtcmemCodec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), p_rtcmem); - loggers::get_instance().log("RtcmemCodec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("RtcmemCodec::decode: ", p_rtcmem); - } - return rc; -} - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_RTCMEM; -} - -int RtcmemPDUCodec::encode(const RTCMEM__PDU__Descriptions::RTCMEM &p_rtcmem, BITSTRING &p_data) { - return _encode(RTCMEM__PDU__Descriptions::RTCMEM_descr_, asn_DEF_RTCMEM, p_rtcmem, p_data); -} - -int RtcmemPDUCodec::decode(const BITSTRING &p_data, RTCMEM__PDU__Descriptions::RTCMEM &p_rtcmem) { - return _decode(RTCMEM__PDU__Descriptions::RTCMEM_descr_, asn_DEF_RTCMEM, p_data, p_rtcmem); -} +#include "RtcmemCodec.hh" +#include "LibItsRtcmem_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int RtcmemCodec::encode(const RTCMEM__PDU__Descriptions::RTCMEM &rtcmem, OCTETSTRING &data) { + loggers::get_instance().log(">>> RtcmemCodec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(rtcmem, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("RtcmemCodec::encode: ", data); + } + return rc; +} + +int RtcmemCodec::decode(const OCTETSTRING &data, RTCMEM__PDU__Descriptions::RTCMEM &p_rtcmem, params *params) { + loggers::get_instance().log_msg(">>> RtcmemCodec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), p_rtcmem); + loggers::get_instance().log("RtcmemCodec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("RtcmemCodec::decode: ", p_rtcmem); + } + return rc; +} + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_RTCMEM; +} + +int RtcmemPDUCodec::encode(const RTCMEM__PDU__Descriptions::RTCMEM &p_rtcmem, BITSTRING &p_data) { + return _encode(RTCMEM__PDU__Descriptions::RTCMEM_descr_, asn_DEF_RTCMEM, p_rtcmem, p_data); +} + +int RtcmemPDUCodec::decode(const BITSTRING &p_data, RTCMEM__PDU__Descriptions::RTCMEM &p_rtcmem) { + return _decode(RTCMEM__PDU__Descriptions::RTCMEM_descr_, asn_DEF_RTCMEM, p_data, p_rtcmem); +} diff --git a/ccsrc/Protocols/Rtcmem/RtcmemCodec.hh b/ccsrc/Protocols/Rtcmem/RtcmemCodec.hh index 21689984148138d47107e36c05adec1a36b70490..d124acada81eeaee7c8d02db732c41b76771ccad 100644 --- a/ccsrc/Protocols/Rtcmem/RtcmemCodec.hh +++ b/ccsrc/Protocols/Rtcmem/RtcmemCodec.hh @@ -1,28 +1,28 @@ -#ifndef RTCMEMCODEC_H -#define RTCMEMCODEC_H - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -#include "LibItsRtcmem_TestSystem.hh" - -class RtcmemPDUCodec : public per_codec { -public: - RtcmemPDUCodec(){}; - virtual int encode(const RTCMEM__PDU__Descriptions::RTCMEM &srem, BITSTRING &data); - virtual int decode(const BITSTRING &data, RTCMEM__PDU__Descriptions::RTCMEM &); -}; - -class RtcmemCodec : public codec { - RtcmemPDUCodec asn_codec; - -public: - RtcmemCodec() : codec(), asn_codec(){}; - virtual ~RtcmemCodec(){}; - - virtual int encode(const RTCMEM__PDU__Descriptions::RTCMEM &srem, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, RTCMEM__PDU__Descriptions::RTCMEM &, params *params = NULL); -}; - -#endif +#ifndef RTCMEMCODEC_H +#define RTCMEMCODEC_H + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +#include "LibItsRtcmem_TestSystem.hh" + +class RtcmemPDUCodec : public per_codec { +public: + RtcmemPDUCodec(){}; + virtual int encode(const RTCMEM__PDU__Descriptions::RTCMEM &srem, BITSTRING &data); + virtual int decode(const BITSTRING &data, RTCMEM__PDU__Descriptions::RTCMEM &); +}; + +class RtcmemCodec : public codec { + RtcmemPDUCodec asn_codec; + +public: + RtcmemCodec() : codec(), asn_codec(){}; + virtual ~RtcmemCodec(){}; + + virtual int encode(const RTCMEM__PDU__Descriptions::RTCMEM &srem, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, RTCMEM__PDU__Descriptions::RTCMEM &, params *params = NULL); +}; + +#endif diff --git a/ccsrc/Protocols/Rtcmem/RtcmemLayer.cc b/ccsrc/Protocols/Rtcmem/RtcmemLayer.cc index bd2536b640708cdb2dc718604493cbfaa8c239f1..3de9c12f77c076d5421f3d580c13a4c73ff352b6 100644 --- a/ccsrc/Protocols/Rtcmem/RtcmemLayer.cc +++ b/ccsrc/Protocols/Rtcmem/RtcmemLayer.cc @@ -19,7 +19,7 @@ RtcmemLayer::RtcmemLayer(const std::string &p_type, const std::string ¶m) registration::get_instance().add_item(p_type, this); } -void RtcmemLayer::sendMsg(const LibItsRtcmem__TestSystem::RtcmemReq &p, params ¶ms) { +void RtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::RtcmemReq &p, params ¶ms) { loggers::get_instance().log_msg(">>> RtcmemLayer::sendMsg: ", p); // Encode rtcmem PDU @@ -40,7 +40,7 @@ void RtcmemLayer::receive_data(OCTETSTRING &data, params ¶ms) { loggers::get_instance().log_msg(">>> RtcmemLayer::receive_data: ", data); // Decode the RTCMEM payload - LibItsRtcmem__TestSystem::RtcmemInd p; + LibItsRtcmem__TypesAndValues::RtcmemInd p; _rtcmem_codec.decode(data, p.msgIn()); if (!p.msgIn().is_bound()) { // Discard it diff --git a/ccsrc/Protocols/Rtcmem/RtcmemLayer.hh b/ccsrc/Protocols/Rtcmem/RtcmemLayer.hh index bf86d5e0ca7ffd633aab68268199fc6ec024aa85..87fc6bd4049fd892de1cabf860b346ba83014bb9 100644 --- a/ccsrc/Protocols/Rtcmem/RtcmemLayer.hh +++ b/ccsrc/Protocols/Rtcmem/RtcmemLayer.hh @@ -28,7 +28,7 @@ public: RtcmemLayer(const std::string &p_type, const std::string ¶m); virtual ~RtcmemLayer(){}; - void sendMsg(const LibItsRtcmem__TestSystem::RtcmemReq &, params ¶ms); + void sendMsg(const LibItsRtcmem__TypesAndValues::RtcmemReq &, params ¶ms); virtual void send_data(OCTETSTRING &data, params ¶ms); virtual void receive_data(OCTETSTRING &data, params &info); diff --git a/ccsrc/Protocols/Rtcmem/RtcmemLayerFactory.hh b/ccsrc/Protocols/Rtcmem/RtcmemLayerFactory.hh index 028b3e5918278505b89b4eabc3ac901d48ae17c0..da037e9b1f8287663380fbc8d88583e7a38687e4 100644 --- a/ccsrc/Protocols/Rtcmem/RtcmemLayerFactory.hh +++ b/ccsrc/Protocols/Rtcmem/RtcmemLayerFactory.hh @@ -1,26 +1,26 @@ -/*! - * \file RtcmemLayerFactory.hh - * \brief Header file for ITS Rtcmem protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "RtcmemLayer.hh" - -class RtcmemLayerFactory : public layer_factory { - static RtcmemLayerFactory _f; - -public: - RtcmemLayerFactory() { - // Register factory - layer_stack_builder::register_layer_factory("Rtcmem", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new RtcmemLayer(p_type, p_param); }; -}; // End of class RtcmemLayerFactory +/*! + * \file RtcmemLayerFactory.hh + * \brief Header file for ITS Rtcmem protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "RtcmemLayer.hh" + +class RtcmemLayerFactory : public layer_factory { + static RtcmemLayerFactory _f; + +public: + RtcmemLayerFactory() { + // Register factory + layer_stack_builder::register_layer_factory("Rtcmem", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new RtcmemLayer(p_type, p_param); }; +}; // End of class RtcmemLayerFactory diff --git a/ccsrc/Protocols/Rtcmem/RtcmemTypes.hh b/ccsrc/Protocols/Rtcmem/RtcmemTypes.hh index 39a1be1cdd688474b4bbcd95d5f9366b494082bd..62a022bd38c3d9d36a6dadd150b5fc9c5d0c803c 100644 --- a/ccsrc/Protocols/Rtcmem/RtcmemTypes.hh +++ b/ccsrc/Protocols/Rtcmem/RtcmemTypes.hh @@ -1,8 +1,8 @@ -#ifndef RTCMEMTYPES_H -#define RTCMEMTYPES_H - -using namespace std; // Required for isnan() -#include "LibItsRtcmem_TestSystem.hh" -#include "LibItsRtcmem_TypesAndValues.hh" - -#endif +#ifndef RTCMEMTYPES_H +#define RTCMEMTYPES_H + +using namespace std; // Required for isnan() +#include "LibItsRtcmem_TestSystem.hh" +#include "LibItsRtcmem_TypesAndValues.hh" + +#endif diff --git a/ccsrc/Protocols/Rtcmem/module.mk b/ccsrc/Protocols/Rtcmem/module.mk index a934c165fa3baac54fbbc4a0c022f157516efb0b..77945c7758734f0f7dd6de60ab5e0132721e68d1 100644 --- a/ccsrc/Protocols/Rtcmem/module.mk +++ b/ccsrc/Protocols/Rtcmem/module.mk @@ -1,3 +1,3 @@ -sources := RtcmemCodec.cc RtcmemLayer.cc -includes := . - +sources := RtcmemCodec.cc RtcmemLayer.cc +includes := . + diff --git a/ccsrc/Protocols/Security/certificates_loader.cc b/ccsrc/Protocols/Security/certificates_loader.cc index e6b4fa3c46b0ca135628f762020702f1db61393d..ba7cea5db91cfc0d29065fd0fc73c92cff230d73 100644 --- a/ccsrc/Protocols/Security/certificates_loader.cc +++ b/ccsrc/Protocols/Security/certificates_loader.cc @@ -1,436 +1,436 @@ -#include -#include - -#include "EtsiTs103097Module.hh" - -#include "certificates_loader.hh" - -#include "etsi_ts103097_certificate_codec.hh" - -#include "sha256.hh" -#include "sha384.hh" - -#include "converter.hh" - -#include "loggers.hh" - -certificates_loader *certificates_loader::instance = nullptr; - -certificates_loader::certificates_loader() - : _certificateExt{".oer"}, _privateKeyExt{".vkey"}, _privateEncKeyExt{".ekey"}, - _full_path(), _is_cache_initialized{false}, _directory_filter{".svn", "._.DS_Store", ".DS_Store"} { - // loggers::get_instance().log(">>> certificates_loader::certificates_loader"); -} // End of ctor - -int certificates_loader::build_path(const std::string &p_root_directory) { - // loggers::get_instance().log(">>> certificates_loader::build_path: '%s'", p_root_directory.c_str()); - - // Build full path - if (!p_root_directory.empty()) { - _full_path = p_root_directory; - if (!std::experimental::filesystem::exists(_full_path) || - !std::experimental::filesystem::is_directory(_full_path)) { // FIXME Coredump when app hasn't the rights to create the directory!!!! - // Create directory - if (!std::experimental::filesystem::create_directory(_full_path)) { - _full_path = "./"; - } else { // Set rights for all users - std::experimental::filesystem::permissions(_full_path, - std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | - std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); - } - } - } else { - _full_path = "./"; - } - std::experimental::filesystem::canonical(_full_path); - // loggers::get_instance().log("certificates_loader::build_path: full path: %s", _full_path.string().c_str()); - if (!std::experimental::filesystem::exists(_full_path)) { - loggers::get_instance().warning("certificates_loader::build_path: Invalid path"); - _full_path.clear(); - return -1; - } - - return 0; -} // End of method build_path - -int certificates_loader::load_certificates(std::map> & p_certificates, - std::map*/, std::string, security_cache_comp> &p_hashed_id8s) { - // loggers::get_instance().log(">>> certificates_loader::load_certificates"); - - // Sanity check - if (_is_cache_initialized) { - return 0; - } - - // Retrieve the list of the files in the path - std::set files; - if (retrieve_certificates_list(files) == -1) { - loggers::get_instance().warning("certificates_loader::load_certificates: Failed to build the list of certificate files"); - return -1; - } - // Build the certificates cache - if (build_certificates_cache(files, p_certificates, p_hashed_id8s) == -1) { - loggers::get_instance().warning("certificates_loader::load_certificates: Failed to build the certificate cache"); - return -1; - } - - _is_cache_initialized = true; - - return 0; -} // End of method load_certificates - -int certificates_loader::retrieve_certificates_list(std::set &p_files) { - // loggers::get_instance().log(">>> certificates_loader::retrieve_certificates_list"); - - // Walk through directories - std::set folders; - for (const std::experimental::filesystem::directory_entry it : std::experimental::filesystem::recursive_directory_iterator(_full_path.string())) { - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Processing directory '%s'", it.path().string().c_str()); - if (std::experimental::filesystem::is_directory(it)) { - std::set::const_iterator i = _directory_filter.find(it.path().filename()); - if (i != _directory_filter.cend()) { - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Exclude directory '%s'", it.path().string().c_str()); - continue; - } - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Add directory '%s'", it.path().string().c_str()); - folders.insert(it.path()); - } - } // End of 'for' statement - - if (folders.size() == 0) { - loggers::get_instance().warning("certificates_loader::retrieve_certificates_list: No folder after filtering"); - folders.insert(_full_path); - } - // Process files - p_files.clear(); - for (std::set::const_reverse_iterator f = folders.crbegin(); f != folders.crend(); ++f) { - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Processing directory '%s'", f->string().c_str()); - for (const std::experimental::filesystem::directory_entry it : std::experimental::filesystem::recursive_directory_iterator(*f)) { - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Processing file '%s'", it.path().filename().string().c_str()); - if (std::experimental::filesystem::is_regular_file(it)) { - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Check extension '%s'", it.path().extension().string().c_str()); - if (it.path().extension().string().compare(_certificateExt) == 0) { - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Add file '%s'", it.path().filename().string().c_str()); - p_files.insert(it); - } - } - } // End of 'for' statement - } // End of 'for' statement - // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: # of files to cache: %d", p_files.size()); - if (p_files.size() == 0) { - loggers::get_instance().warning("certificates_loader::retrieve_certificates_list: No certificate found"); - return -1; - } - - return 0; -} // End of method retrieve_certificates_list - -int certificates_loader::build_certificates_cache(std::set & p_files, - std::map> & p_certificates, - std::map*/, std::string, security_cache_comp> &p_hashed_id8s) { - // loggers::get_instance().log(">>> certificates_loader::build_certificates_cache"); - - std::set::const_iterator it = p_files.cbegin(); - std::pair>::iterator, bool> result; - do { - loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching '%s'", it->string().c_str()); - std::experimental::filesystem::path p = *it; - const std::string & key = p.stem(); - // loggers::get_instance().log("certificates_loader::build_certificates_cache: Key = '%s'", key.c_str()); - - // Load certificate file - it = p_files.find(p.replace_extension(_certificateExt)); - if (it == p_files.cend()) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Certificate file not found for '%s'", key.c_str()); - return -1; - } - // loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching certificate '%s'", it->string().c_str()); - std::ifstream is(it->string(), ios::in | ios::binary); - if (!is.is_open()) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to open certificate file"); - return -1; - } - OCTETSTRING certificate = int2oct(0, std::experimental::filesystem::file_size(*it)); - is.read((char *)static_cast(certificate), certificate.lengthof()); - is.close(); - // Remove items from the list - p_files.erase(it); - - // Load private key file - OCTETSTRING private_key; - p = p.replace_extension(_privateKeyExt); - // loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching private keys '%s'", p.string().c_str()); - is.open(p, ios::in | ios::binary); - if (!is.is_open()) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to open Private key"); - private_key = OCTETSTRING(0, nullptr); - } else { - int size = std::experimental::filesystem::file_size(p); - if ((size != 32) && (size != 48)) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Private key size is incorrect for '%s'", key.c_str()); - return -1; - } - private_key = int2oct(0, size); - is.read((char *)static_cast(private_key), private_key.lengthof()); - is.close(); - } - - // Load private encryption key file if present - OCTETSTRING private_enc_key; - p = p.replace_extension(_privateEncKeyExt); - // loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching private encryption key '%s'", p.string().c_str()); - is.open(p, ios::in | ios::binary); - if (!is.is_open()) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to open Private encryption key file"); - private_enc_key = OCTETSTRING(0, nullptr); - } else { - int size = std::experimental::filesystem::file_size(p); - if (size != 32) { // IEEE Std 1609.2 2017: NistP256 or BrainpoolP256r1 - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Private encryption key size is incorrect for '%s'", key.c_str()); - return -1; - } - private_enc_key = int2oct(0, size); - is.read((char *)static_cast(private_enc_key), private_enc_key.lengthof()); - is.close(); - } - - // Build DB record - etsi_ts103097_certificate_codec codec; - Ieee1609Dot2::CertificateBase decoded_certificate; - codec.decode(certificate, decoded_certificate); - if (!decoded_certificate.is_value()) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to decode certificate for '%s'", key.c_str()); - return -1; - } else { - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Decoded certificate: ", decoded_certificate); - // Prepare all fields - if (!decoded_certificate.toBeSigned().verifyKeyIndicator().ischosen(Ieee1609Dot2::VerificationKeyIndicator::ALT_verificationKey)) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Wrong VerificationKeyIndicator variant for '%s'", key.c_str()); - return -1; - } - OCTETSTRING public_key_x; - OCTETSTRING public_key_y; - OCTETSTRING public_comp_key; // public compressed key, 33 or 49 bytes length, byte #0 indicating compressed-y-0 (0x02) or compressed-y-1 (0x03) - Ieee1609Dot2BaseTypes::PublicVerificationKey &b = decoded_certificate.toBeSigned().verifyKeyIndicator().verificationKey(); - if (b.ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaNistP256)) { - Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = b.ecdsaNistP256(); - fill_public_key_vectors(ec_elliptic_curves::nist_p_256, p, public_comp_key, public_key_x, public_key_y); - } else if (b.ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaBrainpoolP256r1)) { - Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = b.ecdsaBrainpoolP256r1(); - fill_public_key_vectors(ec_elliptic_curves::brainpool_p_256_r1, p, public_comp_key, public_key_x, public_key_y); - } else { // ALT_ecdsaBrainpoolP384r1 - Ieee1609Dot2BaseTypes::EccP384CurvePoint &p = b.ecdsaBrainpoolP384r1(); - fill_public_key_vectors(ec_elliptic_curves::brainpool_p_384_r1, p, public_comp_key, public_key_x, public_key_y); - } - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_key_x: ", public_key_x); - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_key_y: ", public_key_y); - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_comp_key: ", public_comp_key); - - OCTETSTRING public_enc_key_x; - OCTETSTRING public_enc_key_y; - OCTETSTRING public_enc_comp_key; - if (decoded_certificate.toBeSigned().encryptionKey().ispresent()) { - Ieee1609Dot2BaseTypes::PublicEncryptionKey &v = - static_cast(decoded_certificate.toBeSigned().encryptionKey()); - Ieee1609Dot2BaseTypes::BasePublicEncryptionKey &b = v.publicKey(); - if (b.ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesNistP256)) { - Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = v.publicKey().eciesNistP256(); - fill_public_key_vectors(ec_elliptic_curves::nist_p_256, p, public_enc_comp_key, public_enc_key_x, public_enc_key_y); - } else if (b.ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesBrainpoolP256r1)) { - Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = v.publicKey().eciesBrainpoolP256r1(); - fill_public_key_vectors(ec_elliptic_curves::brainpool_p_256_r1, p, public_enc_comp_key, public_enc_key_x, public_enc_key_y); - } - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_enc_key_x: ", public_enc_key_x); - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_enc_key_y: ", public_enc_key_y); - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_enc_comp_key: ", public_enc_comp_key); - } else { - public_enc_key_x = OCTETSTRING(0, nullptr); - public_enc_key_y = OCTETSTRING(0, nullptr); - public_enc_comp_key = OCTETSTRING(0, nullptr); - } - - OCTETSTRING hash_sha_256; // Whole-certificate hash using SHA-256 - sha256 sha; - sha.generate(certificate, hash_sha_256); - loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-256 hash for encryption: ", hash_sha_256); - - OCTETSTRING hash; // Whole-certificate hash - OCTETSTRING hashed_id; // Whole-certificate hashedid-8 - OCTETSTRING issuer; // Certificate issuer - if (public_key_x.lengthof() == 32) { // See IEEE Std 1609.2a-2017 Clause 6.4.3 CertificateBase - hash = hash_sha_256; - loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-256 hash: ", hash); - hashed_id = OCTETSTRING(8, static_cast(hash) + hash.lengthof() - 8); - } else if (public_key_x.lengthof() == 48) { - sha384 sha; - sha.generate(certificate, hash); - loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-384 hash: ", hash); - hashed_id = OCTETSTRING(8, static_cast(hash) + hash.lengthof() - 8); - } else { - hash = OCTETSTRING(0, nullptr); - hash_sha_256 = OCTETSTRING(0, nullptr); - hashed_id = int2oct(0, 8); - } - loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: hash: ", hash); - loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: hashed_id: ", hashed_id); - - if (decoded_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha256AndDigest)) { - issuer = decoded_certificate.issuer().sha256AndDigest(); - } else if (decoded_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha384AndDigest)) { - issuer = decoded_certificate.issuer().sha384AndDigest(); - } else if (decoded_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_self__)) { - OCTETSTRING h; - if (decoded_certificate.issuer().self__() == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { - sha256 sha; - sha.generate(certificate, h); - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-256 hash: ", hash); - } else { - sha384 sha; - sha.generate(certificate, h); - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-384 hash: ", hash); - } - issuer = OCTETSTRING(8, static_cast(h) + h.lengthof() - 8); - } else { - issuer = int2oct(0, 8); - } - loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: issuer: ", issuer); - - // Create new record - security_db_record *p = new security_db_record( - key, - certificate, // Certificate - decoded_certificate, - issuer, // Hashed ID fo the issuer - hash, hash_sha_256, - hashed_id, // Hashed ID - private_key, // Private key - public_key_x, // public keys X-coordinate - public_key_y, // public keys Y-coordinate - public_comp_key, // public compressed key, 33 or 49 bytes length, byte #0 indicating compressed-y-0 (0x02) or compressed-y-1 (0x03) - private_enc_key, // Private encryption key - public_enc_key_x, // Public encryption key X-coordinate - public_enc_key_y, // Public encryption key Y-coordinate - public_enc_comp_key // Public compressed encryption key - ); - result = p_certificates.insert(std::pair>(key, std::unique_ptr(p))); - if (result.second == false) { - loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to insert new record '%s'", key.c_str()); - delete p; - return -1; - } - // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: add key: ", result.first->second.get()->hashed_id()); - // loggers::get_instance().log("certificates_loader::build_certificates_cache: for : %s", result.first->first.c_str()); - p_hashed_id8s.insert(std::pair(result.first->second.get()->hashed_id(), result.first->first)); - /*std::vector v(static_cast(result.first->second.get()->hashed_id()), - result.first->second.get()->hashed_id().lengthof() + static_cast(result.first->second.get()->hashed_id())); - loggers::get_instance().log_to_hexa("security_cache::store_certificate: Converted hashed_id8: ", v.data(), v.size()); - p_hashed_id8s.insert(std::pair, std::string>(v, result.first->first));*/ - } - // Reset pointer - it = p_files.cbegin(); - } while (it != p_files.cend()); - - return 0; -} // End of method build_certificates_cache - -int certificates_loader::save_certificate(const security_db_record &p_certificate) { - loggers::get_instance().log(">>> certificates_loader::save_certificate: certificate_id=%s", p_certificate.certificate_id().c_str()); - loggers::get_instance().log_msg("certificates_loader::save_certificate: hash=", p_certificate.hash()); - loggers::get_instance().log_msg("certificates_loader::save_certificate: hashedid8=", p_certificate.hashed_id()); - - // Certificate file - std::experimental::filesystem::path p(_full_path); - p /= p_certificate.certificate_id(); - p += _certificateExt; - if (std::experimental::filesystem::exists(p)) { - std::experimental::filesystem::remove(p); - } - loggers::get_instance().log("certificates_loader::save_certificate: Certificate file: '%s'", p.string().c_str()); - std::ofstream os(p.string(), ios::out | ios::binary); - os.write((char *)static_cast(p_certificate.certificate()), p_certificate.certificate().lengthof()); - os.close(); - std::experimental::filesystem::permissions(p, std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | - std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); - - // Private key - p = _full_path; - p /= p_certificate.certificate_id(); - p += _privateKeyExt; - if (std::experimental::filesystem::exists(p)) { - std::experimental::filesystem::remove(p); - } - loggers::get_instance().log("certificates_loader::save_certificate: Private key file: '%s'", p.string().c_str()); - os.open(p.string(), ios::out | ios::binary); - loggers::get_instance().log_msg("certificates_loader::save_certificate: Private key content: ", p_certificate.private_key()); - os.write((char *)static_cast(p_certificate.private_key()), p_certificate.private_key().lengthof()); - os.close(); - std::experimental::filesystem::permissions(p, std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | - std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); - - // Private encryption key - if (p_certificate.private_enc_key().lengthof() != 0) { - p = _full_path; - p /= p_certificate.certificate_id(); - p += _privateEncKeyExt; - if (std::experimental::filesystem::exists(p)) { - std::experimental::filesystem::remove(p); - } - loggers::get_instance().log("certificates_loader::save_certificate: Private encryption key file: '%s'", p.string().c_str()); - os.open(p.string(), ios::out | ios::binary); - os.write((char *)static_cast(p_certificate.private_enc_key()), p_certificate.private_enc_key().lengthof()); - os.close(); - std::experimental::filesystem::permissions(p, std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | - std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); - } - - return 0; -} // End of method save_certificate - -void certificates_loader::fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP256CurvePoint &p_ecc_point, - OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) { - loggers::get_instance().log_msg(">>> certificates_loader::fill_public_key_vectors: ", p_ecc_point); - - if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - p_public_comp_key = int2oct(2, 1) + p_ecc_point.compressed__y__0(); - security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__0(), ecc_compressed_mode::compressed_y_0); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - p_public_comp_key = int2oct(3, 1) + p_ecc_point.compressed__y__1(); - security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__1(), ecc_compressed_mode::compressed_y_1); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - p_public_key_x = p_ecc_point.uncompressedP256().x(); - p_public_key_y = p_ecc_point.uncompressedP256().y(); - p_public_comp_key = int2oct(0, 33); - } else { - p_public_key_x = int2oct(0, 32); - p_public_key_y = int2oct(0, 32); - p_public_comp_key = int2oct(0, 33); - } -} -void certificates_loader::fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP384CurvePoint &p_ecc_point, - OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) { - // loggers::get_instance().log_msg(">>> certificates_loader::fill_public_key_vectors: ", p_ecc_point); - - if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__0)) { - p_public_comp_key = int2oct(2, 1) + p_ecc_point.compressed__y__0(); - security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__0(), ecc_compressed_mode::compressed_y_0); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__1)) { - p_public_comp_key = int2oct(3, 1) + p_ecc_point.compressed__y__1(); - security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__1(), ecc_compressed_mode::compressed_y_1); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_uncompressedP384)) { - p_public_key_x = p_ecc_point.uncompressedP384().x(); - p_public_key_y = p_ecc_point.uncompressedP384().y(); - p_public_comp_key = int2oct(0, 49); - } else { - p_public_key_x = int2oct(0, 48); - p_public_key_y = int2oct(0, 48); - p_public_comp_key = int2oct(0, 49); - } -} +#include +#include + +#include "EtsiTs103097Module.hh" + +#include "certificates_loader.hh" + +#include "etsi_ts103097_certificate_codec.hh" + +#include "sha256.hh" +#include "sha384.hh" + +#include "converter.hh" + +#include "loggers.hh" + +certificates_loader *certificates_loader::instance = nullptr; + +certificates_loader::certificates_loader() + : _certificateExt{".oer"}, _privateKeyExt{".vkey"}, _privateEncKeyExt{".ekey"}, + _full_path(), _is_cache_initialized{false}, _directory_filter{".svn", "._.DS_Store", ".DS_Store"} { + // loggers::get_instance().log(">>> certificates_loader::certificates_loader"); +} // End of ctor + +int certificates_loader::build_path(const std::string &p_root_directory) { + // loggers::get_instance().log(">>> certificates_loader::build_path: '%s'", p_root_directory.c_str()); + + // Build full path + if (!p_root_directory.empty()) { + _full_path = p_root_directory; + if (!std::experimental::filesystem::exists(_full_path) || + !std::experimental::filesystem::is_directory(_full_path)) { // FIXME Coredump when app hasn't the rights to create the directory!!!! + // Create directory + if (!std::experimental::filesystem::create_directory(_full_path)) { + _full_path = "./"; + } else { // Set rights for all users + std::experimental::filesystem::permissions(_full_path, + std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | + std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); + } + } + } else { + _full_path = "./"; + } + std::experimental::filesystem::canonical(_full_path); + // loggers::get_instance().log("certificates_loader::build_path: full path: %s", _full_path.string().c_str()); + if (!std::experimental::filesystem::exists(_full_path)) { + loggers::get_instance().warning("certificates_loader::build_path: Invalid path"); + _full_path.clear(); + return -1; + } + + return 0; +} // End of method build_path + +int certificates_loader::load_certificates(std::map> & p_certificates, + std::map*/, std::string, security_cache_comp> &p_hashed_id8s) { + // loggers::get_instance().log(">>> certificates_loader::load_certificates"); + + // Sanity check + if (_is_cache_initialized) { + return 0; + } + + // Retrieve the list of the files in the path + std::set files; + if (retrieve_certificates_list(files) == -1) { + loggers::get_instance().warning("certificates_loader::load_certificates: Failed to build the list of certificate files"); + return -1; + } + // Build the certificates cache + if (build_certificates_cache(files, p_certificates, p_hashed_id8s) == -1) { + loggers::get_instance().warning("certificates_loader::load_certificates: Failed to build the certificate cache"); + return -1; + } + + _is_cache_initialized = true; + + return 0; +} // End of method load_certificates + +int certificates_loader::retrieve_certificates_list(std::set &p_files) { + // loggers::get_instance().log(">>> certificates_loader::retrieve_certificates_list"); + + // Walk through directories + std::set folders; + for (const std::experimental::filesystem::directory_entry it : std::experimental::filesystem::recursive_directory_iterator(_full_path.string())) { + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Processing directory '%s'", it.path().string().c_str()); + if (std::experimental::filesystem::is_directory(it)) { + std::set::const_iterator i = _directory_filter.find(it.path().filename()); + if (i != _directory_filter.cend()) { + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Exclude directory '%s'", it.path().string().c_str()); + continue; + } + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Add directory '%s'", it.path().string().c_str()); + folders.insert(it.path()); + } + } // End of 'for' statement + + if (folders.size() == 0) { + loggers::get_instance().warning("certificates_loader::retrieve_certificates_list: No folder after filtering"); + folders.insert(_full_path); + } + // Process files + p_files.clear(); + for (std::set::const_reverse_iterator f = folders.crbegin(); f != folders.crend(); ++f) { + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Processing directory '%s'", f->string().c_str()); + for (const std::experimental::filesystem::directory_entry it : std::experimental::filesystem::recursive_directory_iterator(*f)) { + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Processing file '%s'", it.path().filename().string().c_str()); + if (std::experimental::filesystem::is_regular_file(it)) { + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Check extension '%s'", it.path().extension().string().c_str()); + if (it.path().extension().string().compare(_certificateExt) == 0) { + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: Add file '%s'", it.path().filename().string().c_str()); + p_files.insert(it); + } + } + } // End of 'for' statement + } // End of 'for' statement + // loggers::get_instance().log("certificates_loader::retrieve_certificates_list: # of files to cache: %d", p_files.size()); + if (p_files.size() == 0) { + loggers::get_instance().warning("certificates_loader::retrieve_certificates_list: No certificate found"); + return -1; + } + + return 0; +} // End of method retrieve_certificates_list + +int certificates_loader::build_certificates_cache(std::set & p_files, + std::map> & p_certificates, + std::map*/, std::string, security_cache_comp> &p_hashed_id8s) { + // loggers::get_instance().log(">>> certificates_loader::build_certificates_cache"); + + std::set::const_iterator it = p_files.cbegin(); + std::pair>::iterator, bool> result; + do { + loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching '%s'", it->string().c_str()); + std::experimental::filesystem::path p = *it; + const std::string & key = p.stem(); + // loggers::get_instance().log("certificates_loader::build_certificates_cache: Key = '%s'", key.c_str()); + + // Load certificate file + it = p_files.find(p.replace_extension(_certificateExt)); + if (it == p_files.cend()) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Certificate file not found for '%s'", key.c_str()); + return -1; + } + // loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching certificate '%s'", it->string().c_str()); + std::ifstream is(it->string(), ios::in | ios::binary); + if (!is.is_open()) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to open certificate file"); + return -1; + } + OCTETSTRING certificate = int2oct(0, std::experimental::filesystem::file_size(*it)); + is.read((char *)static_cast(certificate), certificate.lengthof()); + is.close(); + // Remove items from the list + p_files.erase(it); + + // Load private key file + OCTETSTRING private_key; + p = p.replace_extension(_privateKeyExt); + // loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching private keys '%s'", p.string().c_str()); + is.open(p, ios::in | ios::binary); + if (!is.is_open()) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to open Private key"); + private_key = OCTETSTRING(0, nullptr); + } else { + int size = std::experimental::filesystem::file_size(p); + if ((size != 32) && (size != 48)) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Private key size is incorrect for '%s'", key.c_str()); + return -1; + } + private_key = int2oct(0, size); + is.read((char *)static_cast(private_key), private_key.lengthof()); + is.close(); + } + + // Load private encryption key file if present + OCTETSTRING private_enc_key; + p = p.replace_extension(_privateEncKeyExt); + // loggers::get_instance().log("certificates_loader::build_certificates_cache: Caching private encryption key '%s'", p.string().c_str()); + is.open(p, ios::in | ios::binary); + if (!is.is_open()) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to open Private encryption key file"); + private_enc_key = OCTETSTRING(0, nullptr); + } else { + int size = std::experimental::filesystem::file_size(p); + if (size != 32) { // IEEE Std 1609.2 2017: NistP256 or BrainpoolP256r1 + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Private encryption key size is incorrect for '%s'", key.c_str()); + return -1; + } + private_enc_key = int2oct(0, size); + is.read((char *)static_cast(private_enc_key), private_enc_key.lengthof()); + is.close(); + } + + // Build DB record + etsi_ts103097_certificate_codec codec; + Ieee1609Dot2::CertificateBase decoded_certificate; + codec.decode(certificate, decoded_certificate); + if (!decoded_certificate.is_value()) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to decode certificate for '%s'", key.c_str()); + return -1; + } else { + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Decoded certificate: ", decoded_certificate); + // Prepare all fields + if (!decoded_certificate.toBeSigned().verifyKeyIndicator().ischosen(Ieee1609Dot2::VerificationKeyIndicator::ALT_verificationKey)) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Wrong VerificationKeyIndicator variant for '%s'", key.c_str()); + return -1; + } + OCTETSTRING public_key_x; + OCTETSTRING public_key_y; + OCTETSTRING public_comp_key; // public compressed key, 33 or 49 bytes length, byte #0 indicating compressed-y-0 (0x02) or compressed-y-1 (0x03) + Ieee1609Dot2BaseTypes::PublicVerificationKey &b = decoded_certificate.toBeSigned().verifyKeyIndicator().verificationKey(); + if (b.ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaNistP256)) { + Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = b.ecdsaNistP256(); + fill_public_key_vectors(ec_elliptic_curves::nist_p_256, p, public_comp_key, public_key_x, public_key_y); + } else if (b.ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaBrainpoolP256r1)) { + Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = b.ecdsaBrainpoolP256r1(); + fill_public_key_vectors(ec_elliptic_curves::brainpool_p_256_r1, p, public_comp_key, public_key_x, public_key_y); + } else { // ALT_ecdsaBrainpoolP384r1 + Ieee1609Dot2BaseTypes::EccP384CurvePoint &p = b.ecdsaBrainpoolP384r1(); + fill_public_key_vectors(ec_elliptic_curves::brainpool_p_384_r1, p, public_comp_key, public_key_x, public_key_y); + } + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_key_x: ", public_key_x); + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_key_y: ", public_key_y); + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_comp_key: ", public_comp_key); + + OCTETSTRING public_enc_key_x; + OCTETSTRING public_enc_key_y; + OCTETSTRING public_enc_comp_key; + if (decoded_certificate.toBeSigned().encryptionKey().ispresent()) { + Ieee1609Dot2BaseTypes::PublicEncryptionKey &v = + static_cast(decoded_certificate.toBeSigned().encryptionKey()); + Ieee1609Dot2BaseTypes::BasePublicEncryptionKey &b = v.publicKey(); + if (b.ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesNistP256)) { + Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = v.publicKey().eciesNistP256(); + fill_public_key_vectors(ec_elliptic_curves::nist_p_256, p, public_enc_comp_key, public_enc_key_x, public_enc_key_y); + } else if (b.ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesBrainpoolP256r1)) { + Ieee1609Dot2BaseTypes::EccP256CurvePoint &p = v.publicKey().eciesBrainpoolP256r1(); + fill_public_key_vectors(ec_elliptic_curves::brainpool_p_256_r1, p, public_enc_comp_key, public_enc_key_x, public_enc_key_y); + } + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_enc_key_x: ", public_enc_key_x); + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_enc_key_y: ", public_enc_key_y); + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: public_enc_comp_key: ", public_enc_comp_key); + } else { + public_enc_key_x = OCTETSTRING(0, nullptr); + public_enc_key_y = OCTETSTRING(0, nullptr); + public_enc_comp_key = OCTETSTRING(0, nullptr); + } + + OCTETSTRING hash_sha_256; // Whole-certificate hash using SHA-256 + sha256 sha; + sha.generate(certificate, hash_sha_256); + loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-256 hash for encryption: ", hash_sha_256); + + OCTETSTRING hash; // Whole-certificate hash + OCTETSTRING hashed_id; // Whole-certificate hashedid-8 + OCTETSTRING issuer; // Certificate issuer + if (public_key_x.lengthof() == 32) { // See IEEE Std 1609.2a-2017 Clause 6.4.3 CertificateBase + hash = hash_sha_256; + loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-256 hash: ", hash); + hashed_id = OCTETSTRING(8, static_cast(hash) + hash.lengthof() - 8); + } else if (public_key_x.lengthof() == 48) { + sha384 sha; + sha.generate(certificate, hash); + loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-384 hash: ", hash); + hashed_id = OCTETSTRING(8, static_cast(hash) + hash.lengthof() - 8); + } else { + hash = OCTETSTRING(0, nullptr); + hash_sha_256 = OCTETSTRING(0, nullptr); + hashed_id = int2oct(0, 8); + } + loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: hash: ", hash); + loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: hashed_id: ", hashed_id); + + if (decoded_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha256AndDigest)) { + issuer = decoded_certificate.issuer().sha256AndDigest(); + } else if (decoded_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha384AndDigest)) { + issuer = decoded_certificate.issuer().sha384AndDigest(); + } else if (decoded_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_self__)) { + OCTETSTRING h; + if (decoded_certificate.issuer().self__() == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { + sha256 sha; + sha.generate(certificate, h); + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-256 hash: ", hash); + } else { + sha384 sha; + sha.generate(certificate, h); + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: Whole-certificate SHA-384 hash: ", hash); + } + issuer = OCTETSTRING(8, static_cast(h) + h.lengthof() - 8); + } else { + issuer = int2oct(0, 8); + } + loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: issuer: ", issuer); + + // Create new record + security_db_record *p = new security_db_record( + key, + certificate, // Certificate + decoded_certificate, + issuer, // Hashed ID fo the issuer + hash, hash_sha_256, + hashed_id, // Hashed ID + private_key, // Private key + public_key_x, // public keys X-coordinate + public_key_y, // public keys Y-coordinate + public_comp_key, // public compressed key, 33 or 49 bytes length, byte #0 indicating compressed-y-0 (0x02) or compressed-y-1 (0x03) + private_enc_key, // Private encryption key + public_enc_key_x, // Public encryption key X-coordinate + public_enc_key_y, // Public encryption key Y-coordinate + public_enc_comp_key // Public compressed encryption key + ); + result = p_certificates.insert(std::pair>(key, std::unique_ptr(p))); + if (result.second == false) { + loggers::get_instance().warning("certificates_loader::build_certificates_cache: Failed to insert new record '%s'", key.c_str()); + delete p; + return -1; + } + // loggers::get_instance().log_msg("certificates_loader::build_certificates_cache: add key: ", result.first->second.get()->hashed_id()); + // loggers::get_instance().log("certificates_loader::build_certificates_cache: for : %s", result.first->first.c_str()); + p_hashed_id8s.insert(std::pair(result.first->second.get()->hashed_id(), result.first->first)); + /*std::vector v(static_cast(result.first->second.get()->hashed_id()), + result.first->second.get()->hashed_id().lengthof() + static_cast(result.first->second.get()->hashed_id())); + loggers::get_instance().log_to_hexa("security_cache::store_certificate: Converted hashed_id8: ", v.data(), v.size()); + p_hashed_id8s.insert(std::pair, std::string>(v, result.first->first));*/ + } + // Reset pointer + it = p_files.cbegin(); + } while (it != p_files.cend()); + + return 0; +} // End of method build_certificates_cache + +int certificates_loader::save_certificate(const security_db_record &p_certificate) { + loggers::get_instance().log(">>> certificates_loader::save_certificate: certificate_id=%s", p_certificate.certificate_id().c_str()); + loggers::get_instance().log_msg("certificates_loader::save_certificate: hash=", p_certificate.hash()); + loggers::get_instance().log_msg("certificates_loader::save_certificate: hashedid8=", p_certificate.hashed_id()); + + // Certificate file + std::experimental::filesystem::path p(_full_path); + p /= p_certificate.certificate_id(); + p += _certificateExt; + if (std::experimental::filesystem::exists(p)) { + std::experimental::filesystem::remove(p); + } + loggers::get_instance().log("certificates_loader::save_certificate: Certificate file: '%s'", p.string().c_str()); + std::ofstream os(p.string(), ios::out | ios::binary); + os.write((char *)static_cast(p_certificate.certificate()), p_certificate.certificate().lengthof()); + os.close(); + std::experimental::filesystem::permissions(p, std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | + std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); + + // Private key + p = _full_path; + p /= p_certificate.certificate_id(); + p += _privateKeyExt; + if (std::experimental::filesystem::exists(p)) { + std::experimental::filesystem::remove(p); + } + loggers::get_instance().log("certificates_loader::save_certificate: Private key file: '%s'", p.string().c_str()); + os.open(p.string(), ios::out | ios::binary); + loggers::get_instance().log_msg("certificates_loader::save_certificate: Private key content: ", p_certificate.private_key()); + os.write((char *)static_cast(p_certificate.private_key()), p_certificate.private_key().lengthof()); + os.close(); + std::experimental::filesystem::permissions(p, std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | + std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); + + // Private encryption key + if (p_certificate.private_enc_key().lengthof() != 0) { + p = _full_path; + p /= p_certificate.certificate_id(); + p += _privateEncKeyExt; + if (std::experimental::filesystem::exists(p)) { + std::experimental::filesystem::remove(p); + } + loggers::get_instance().log("certificates_loader::save_certificate: Private encryption key file: '%s'", p.string().c_str()); + os.open(p.string(), ios::out | ios::binary); + os.write((char *)static_cast(p_certificate.private_enc_key()), p_certificate.private_enc_key().lengthof()); + os.close(); + std::experimental::filesystem::permissions(p, std::experimental::filesystem::perms::add_perms | std::experimental::filesystem::perms::owner_all | + std::experimental::filesystem::perms::group_all | std::experimental::filesystem::perms::others_all); + } + + return 0; +} // End of method save_certificate + +void certificates_loader::fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP256CurvePoint &p_ecc_point, + OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) { + loggers::get_instance().log_msg(">>> certificates_loader::fill_public_key_vectors: ", p_ecc_point); + + if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + p_public_comp_key = int2oct(2, 1) + p_ecc_point.compressed__y__0(); + security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__0(), ecc_compressed_mode::compressed_y_0); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + p_public_comp_key = int2oct(3, 1) + p_ecc_point.compressed__y__1(); + security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__1(), ecc_compressed_mode::compressed_y_1); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + p_public_key_x = p_ecc_point.uncompressedP256().x(); + p_public_key_y = p_ecc_point.uncompressedP256().y(); + p_public_comp_key = int2oct(0, 33); + } else { + p_public_key_x = int2oct(0, 32); + p_public_key_y = int2oct(0, 32); + p_public_comp_key = int2oct(0, 33); + } +} +void certificates_loader::fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP384CurvePoint &p_ecc_point, + OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) { + // loggers::get_instance().log_msg(">>> certificates_loader::fill_public_key_vectors: ", p_ecc_point); + + if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__0)) { + p_public_comp_key = int2oct(2, 1) + p_ecc_point.compressed__y__0(); + security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__0(), ecc_compressed_mode::compressed_y_0); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__1)) { + p_public_comp_key = int2oct(3, 1) + p_ecc_point.compressed__y__1(); + security_ecc ecc(p_elliptic_curve, p_ecc_point.compressed__y__1(), ecc_compressed_mode::compressed_y_1); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + } else if (p_ecc_point.ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_uncompressedP384)) { + p_public_key_x = p_ecc_point.uncompressedP384().x(); + p_public_key_y = p_ecc_point.uncompressedP384().y(); + p_public_comp_key = int2oct(0, 49); + } else { + p_public_key_x = int2oct(0, 48); + p_public_key_y = int2oct(0, 48); + p_public_comp_key = int2oct(0, 49); + } +} diff --git a/ccsrc/Protocols/Security/certificates_loader.hh b/ccsrc/Protocols/Security/certificates_loader.hh index f5beb894c7be5cc451f29a09b6e26f8e94a84594..a6bd969953348621f3cb1ee22f8f13cf566b05b3 100644 --- a/ccsrc/Protocols/Security/certificates_loader.hh +++ b/ccsrc/Protocols/Security/certificates_loader.hh @@ -1,86 +1,86 @@ -/*! - * \file certificate_loader.hh - * \brief Header file for ITS certificates loader definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - * \remark Use xxd -p -c32 to make a hexdump or do the reverse (e.g. xxd -p -c32 CERT_IUT_A_RCA.vkey) - */ -#pragma once - -#include -#include -#include -#include - -#include - -#include "security_cache.hh" -#include "security_db_record.hh" -#include "security_ecc.hh" - -namespace Ieee1609Dot2BaseTypes { - class EccP256CurvePoint; //! Declare TITAN class - class EccP384CurvePoint; //! Declare TITAN class -} // namespace Ieee1609Dot2BaseTypes - -/*! - * \class certificates_loader - * \brief This class provides mechanism to load the certificates from the filesystem according the struecture defined in ETSI TS 103 099 - * \remark Singleton pattern - */ -class certificates_loader { - std::string _certificateExt; //! COER encoding certificate extension. Default: .oer - std::string _privateKeyExt; //! Private signing key extension. Default: .vkey - std::string _privateEncKeyExt; //! Private cyphering key extension. Default: .ekey - std::experimental::filesystem::path _full_path; //! The full folder path to load certificates - bool _is_cache_initialized; //! Set to true when certificates are successfully loaded from file system - std::set _directory_filter; //! Directory filter (for local development purposes only) - static certificates_loader * instance; //! Unique static object reference of this class - - /*! - * \brief Default private ctor - */ - certificates_loader(); - /*! - * \brief Default private dtor - */ - ~certificates_loader() { - if (instance != NULL) { - delete instance; - instance = NULL; - } - }; - -public: /*! \publicsection */ - /*! - * \brief Public accessor to the single object reference - */ - inline static certificates_loader &get_instance() { - if (instance == NULL) - instance = new certificates_loader(); - return *instance; - }; - - int build_path(const std::string &p_root_directory); - - int load_certificates(std::map> & p_certificates, - std::map*/, std::string, security_cache_comp> &p_hashed_id8s); - // int load_certificate(std::unique_ptr >& p_certificate, std::map& p_hashed_id8s); - int save_certificate(const security_db_record &p_certificate); - -private: - int retrieve_certificates_list(std::set &p_files); - - int build_certificates_cache(std::set & p_files, - std::map> & p_certificates, - std::map*/, std::string, security_cache_comp> &p_hashed_id8s); - - void fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP256CurvePoint &p_ecc_point, - OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y); - void fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP384CurvePoint &p_ecc_point, - OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y); -}; // End of class certificates_loader +/*! + * \file certificate_loader.hh + * \brief Header file for ITS certificates loader definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + * \remark Use xxd -p -c32 to make a hexdump or do the reverse (e.g. xxd -p -c32 CERT_IUT_A_RCA.vkey) + */ +#pragma once + +#include +#include +#include +#include + +#include + +#include "security_cache.hh" +#include "security_db_record.hh" +#include "security_ecc.hh" + +namespace Ieee1609Dot2BaseTypes { + class EccP256CurvePoint; //! Declare TITAN class + class EccP384CurvePoint; //! Declare TITAN class +} // namespace Ieee1609Dot2BaseTypes + +/*! + * \class certificates_loader + * \brief This class provides mechanism to load the certificates from the filesystem according the struecture defined in ETSI TS 103 099 + * \remark Singleton pattern + */ +class certificates_loader { + std::string _certificateExt; //! COER encoding certificate extension. Default: .oer + std::string _privateKeyExt; //! Private signing key extension. Default: .vkey + std::string _privateEncKeyExt; //! Private cyphering key extension. Default: .ekey + std::experimental::filesystem::path _full_path; //! The full folder path to load certificates + bool _is_cache_initialized; //! Set to true when certificates are successfully loaded from file system + std::set _directory_filter; //! Directory filter (for local development purposes only) + static certificates_loader * instance; //! Unique static object reference of this class + + /*! + * \brief Default private ctor + */ + certificates_loader(); + /*! + * \brief Default private dtor + */ + ~certificates_loader() { + if (instance != NULL) { + delete instance; + instance = NULL; + } + }; + +public: /*! \publicsection */ + /*! + * \brief Public accessor to the single object reference + */ + inline static certificates_loader &get_instance() { + if (instance == NULL) + instance = new certificates_loader(); + return *instance; + }; + + int build_path(const std::string &p_root_directory); + + int load_certificates(std::map> & p_certificates, + std::map*/, std::string, security_cache_comp> &p_hashed_id8s); + // int load_certificate(std::unique_ptr >& p_certificate, std::map& p_hashed_id8s); + int save_certificate(const security_db_record &p_certificate); + +private: + int retrieve_certificates_list(std::set &p_files); + + int build_certificates_cache(std::set & p_files, + std::map> & p_certificates, + std::map*/, std::string, security_cache_comp> &p_hashed_id8s); + + void fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP256CurvePoint &p_ecc_point, + OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y); + void fill_public_key_vectors(const ec_elliptic_curves p_elliptic_curve, const Ieee1609Dot2BaseTypes::EccP384CurvePoint &p_ecc_point, + OCTETSTRING &p_public_comp_key, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y); +}; // End of class certificates_loader diff --git a/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.cc b/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.cc index 388b9c55588bbea4c0c655bc5043c61bd58c2dc7..4ffd84152c552ffb3220d1092f30b598baef855a 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.cc @@ -1,28 +1,28 @@ -#include "etsi_ts102941_base_types_public_keys.hh" - -#include "loggers.hh" - -int etsi_ts102941_base_types_public_keys::encode(const EtsiTs102941BaseTypes::PublicKeys &p_public_keys, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_base_types_public_keys::encode: %s", p_public_keys.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_public_keys.encode(*p_public_keys.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_base_types_public_keys::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_base_types_public_keys::decode(const OCTETSTRING &p_data, EtsiTs102941BaseTypes::PublicKeys &p_public_keys, params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_base_types_public_keys::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_public_keys.decode(*p_public_keys.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_base_types_public_keys::decode: ", (const Base_Type &)p_public_keys); - return 0; -} +#include "etsi_ts102941_base_types_public_keys.hh" + +#include "loggers.hh" + +int etsi_ts102941_base_types_public_keys::encode(const EtsiTs102941BaseTypes::PublicKeys &p_public_keys, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_base_types_public_keys::encode: %s", p_public_keys.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_public_keys.encode(*p_public_keys.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_base_types_public_keys::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_base_types_public_keys::decode(const OCTETSTRING &p_data, EtsiTs102941BaseTypes::PublicKeys &p_public_keys, params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_base_types_public_keys::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_public_keys.decode(*p_public_keys.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_base_types_public_keys::decode: ", (const Base_Type &)p_public_keys); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.hh b/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.hh index d5c6e368755802cbac3a5ebb0235d3874e4b3025..4719f189205b2856821314f03681a6d3caebb296 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_base_types_public_keys.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941BaseTypes.hh" - -class etsi_ts102941_base_types_public_keys : public codec { -public: - explicit etsi_ts102941_base_types_public_keys() : codec(){}; - virtual ~etsi_ts102941_base_types_public_keys(){}; - - virtual int encode(const EtsiTs102941BaseTypes::PublicKeys &p_public_keys, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941BaseTypes::PublicKeys &p_public_keys, params *p_params = NULL); -}; // End of class etsi_ts102941_base_types_public_keys +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941BaseTypes.hh" + +class etsi_ts102941_base_types_public_keys : public codec { +public: + explicit etsi_ts102941_base_types_public_keys() : codec(){}; + virtual ~etsi_ts102941_base_types_public_keys(){}; + + virtual int encode(const EtsiTs102941BaseTypes::PublicKeys &p_public_keys, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941BaseTypes::PublicKeys &p_public_keys, params *p_params = NULL); +}; // End of class etsi_ts102941_base_types_public_keys diff --git a/ccsrc/Protocols/Security/etsi_ts102941_data_codec.cc b/ccsrc/Protocols/Security/etsi_ts102941_data_codec.cc index 69ba80d0f2606c3fbcd67a68adf34798e08f281a..68e461b96b21af05cfd826ac3c1d273e2a690b93 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_data_codec.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_data_codec.cc @@ -1,28 +1,28 @@ -#include "etsi_ts102941_data_codec.hh" - -#include "loggers.hh" - -int etsi_ts102941_data_codec::encode(const EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_data_codec::encode: %s", p_etsi_ts_102941_data.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_etsi_ts_102941_data.encode(*p_etsi_ts_102941_data.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_data_codec::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_data_codec::decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data, params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_data_codec::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_etsi_ts_102941_data.decode(*p_etsi_ts_102941_data.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_data_codec::decode: ", (const Base_Type &)p_etsi_ts_102941_data); - return 0; -} +#include "etsi_ts102941_data_codec.hh" + +#include "loggers.hh" + +int etsi_ts102941_data_codec::encode(const EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_data_codec::encode: %s", p_etsi_ts_102941_data.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_etsi_ts_102941_data.encode(*p_etsi_ts_102941_data.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_data_codec::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_data_codec::decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_102941_data, params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_data_codec::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_etsi_ts_102941_data.decode(*p_etsi_ts_102941_data.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_data_codec::decode: ", (const Base_Type &)p_etsi_ts_102941_data); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_data_codec.hh b/ccsrc/Protocols/Security/etsi_ts102941_data_codec.hh index f17b180798166b60b716e971263c17a33cddd634..c2b31c6c6049ee5461c596ec2ce580f7243206f5 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_data_codec.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_data_codec.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941MessagesCa.hh" - -class etsi_ts102941_data_codec : public codec { -public: - explicit etsi_ts102941_data_codec() : codec(){}; - virtual ~etsi_ts102941_data_codec(){}; - - virtual int encode(const EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_10291_data, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_10291_data, params *p_params = NULL); -}; // End of class etsi_ts102941_data_codec +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941MessagesCa.hh" + +class etsi_ts102941_data_codec : public codec { +public: + explicit etsi_ts102941_data_codec() : codec(){}; + virtual ~etsi_ts102941_data_codec(){}; + + virtual int encode(const EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_10291_data, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941Data &p_etsi_ts_10291_data, params *p_params = NULL); +}; // End of class etsi_ts102941_data_codec diff --git a/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.cc b/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.cc index 3ace679cdef4eed61bab1db1f5aa62f845d0e1ba..877c6939e0b3071c7dc15644302cfea1f566c5a5 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.cc @@ -1,29 +1,29 @@ -#include "etsi_ts102941_data_content_codec.hh" - -#include "loggers.hh" - -int etsi_ts102941_data_content_codec::encode(const EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_data_content_codec::encode: %s", p_etsi_ts_10291_data_content.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_etsi_ts_10291_data_content.encode(*p_etsi_ts_10291_data_content.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_data_content_codec::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_data_content_codec::decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_data_content_codec::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_etsi_ts_10291_data_content.decode(*p_etsi_ts_10291_data_content.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_data_content_codec::decode: ", (const Base_Type &)p_etsi_ts_10291_data_content); - return 0; -} +#include "etsi_ts102941_data_content_codec.hh" + +#include "loggers.hh" + +int etsi_ts102941_data_content_codec::encode(const EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_data_content_codec::encode: %s", p_etsi_ts_10291_data_content.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_etsi_ts_10291_data_content.encode(*p_etsi_ts_10291_data_content.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_data_content_codec::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_data_content_codec::decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_data_content_codec::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_etsi_ts_10291_data_content.decode(*p_etsi_ts_10291_data_content.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_data_content_codec::decode: ", (const Base_Type &)p_etsi_ts_10291_data_content); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.hh b/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.hh index 4194ee008327a086f5e73fe41c9ba96a7ef4ef51..db7005fd65ae9e23cdac9c01e278c2c780675635 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_data_content_codec.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941MessagesCa.hh" - -class etsi_ts102941_data_content_codec : public codec { -public: - explicit etsi_ts102941_data_content_codec() : codec(){}; - virtual ~etsi_ts102941_data_content_codec(){}; - - virtual int encode(const EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, params *p_params = NULL); -}; // End of class etsi_ts102941_data_content_codec +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941MessagesCa.hh" + +class etsi_ts102941_data_content_codec : public codec { +public: + explicit etsi_ts102941_data_content_codec() : codec(){}; + virtual ~etsi_ts102941_data_content_codec(){}; + + virtual int encode(const EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941MessagesCa::EtsiTs102941DataContent &p_etsi_ts_10291_data_content, params *p_params = NULL); +}; // End of class etsi_ts102941_data_content_codec diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.cc index f0db94a0387812cbc9f1dae759974c656eaad52b..5fa3aa9153e6d9e5055317abdacff370c9884252 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.cc @@ -1,29 +1,29 @@ -#include "etsi_ts102941_types_authorization_inner_request.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_authorization_inner_request::encode(const EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_authorization_inner_request::encode: %s", p_inner_request.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_inner_request.encode(*p_inner_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_authorization_inner_request::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_authorization_inner_request::decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_inner_request::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_inner_request.decode(*p_inner_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_inner_request::decode: ", (const Base_Type &)p_inner_request); - return 0; -} +#include "etsi_ts102941_types_authorization_inner_request.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_authorization_inner_request::encode(const EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_authorization_inner_request::encode: %s", p_inner_request.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_inner_request.encode(*p_inner_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_authorization_inner_request::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_authorization_inner_request::decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_inner_request::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_inner_request.decode(*p_inner_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_inner_request::decode: ", (const Base_Type &)p_inner_request); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.hh index bd785b7c819a068b07298118e0ed234363a9d1d5..ae12a07f1f2a60149029bd87d94aa862b11fd9cc 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_request.hh @@ -1,17 +1,17 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesAuthorization.hh" - -class etsi_ts102941_types_authorization_inner_request - : public codec { -public: - explicit etsi_ts102941_types_authorization_inner_request() - : codec(){}; - virtual ~etsi_ts102941_types_authorization_inner_request(){}; - - virtual int encode(const EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, params *p_params = NULL); -}; // End of class etsi_ts102941_types_authorization_inner_request +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesAuthorization.hh" + +class etsi_ts102941_types_authorization_inner_request + : public codec { +public: + explicit etsi_ts102941_types_authorization_inner_request() + : codec(){}; + virtual ~etsi_ts102941_types_authorization_inner_request(){}; + + virtual int encode(const EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtRequest &p_inner_request, params *p_params = NULL); +}; // End of class etsi_ts102941_types_authorization_inner_request diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.cc index c0fdb80583258ba064314ba76d5f264ea18add35..09fbc8657dc8d682bc3d8fe3b57296ef6384381a 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.cc @@ -1,29 +1,29 @@ -#include "etsi_ts102941_types_authorization_inner_response.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_authorization_inner_response::encode(const EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_authorization_inner_response::encode: %s", p_inner_response.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_inner_response.encode(*p_inner_response.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_authorization_inner_response::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_authorization_inner_response::decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_inner_response::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_inner_response.decode(*p_inner_response.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_inner_response::decode: ", (const Base_Type &)p_inner_response); - return 0; -} +#include "etsi_ts102941_types_authorization_inner_response.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_authorization_inner_response::encode(const EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_authorization_inner_response::encode: %s", p_inner_response.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_inner_response.encode(*p_inner_response.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_authorization_inner_response::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_authorization_inner_response::decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_inner_response::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_inner_response.decode(*p_inner_response.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_inner_response::decode: ", (const Base_Type &)p_inner_response); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.hh index 4bf4f87519bff039b985ae2f7246c146047f3a3c..2f0161f5d5cd4f267248000eb1d9e2d9ffccf3ef 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_inner_response.hh @@ -1,17 +1,17 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesAuthorization.hh" - -class etsi_ts102941_types_authorization_inner_response - : public codec { -public: - explicit etsi_ts102941_types_authorization_inner_response() - : codec(){}; - virtual ~etsi_ts102941_types_authorization_inner_response(){}; - - virtual int encode(const EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, params *p_params = NULL); -}; // End of class etsi_ts102941_types_authorization_inner_response +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesAuthorization.hh" + +class etsi_ts102941_types_authorization_inner_response + : public codec { +public: + explicit etsi_ts102941_types_authorization_inner_response() + : codec(){}; + virtual ~etsi_ts102941_types_authorization_inner_response(){}; + + virtual int encode(const EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::InnerAtResponse &p_inner_response, params *p_params = NULL); +}; // End of class etsi_ts102941_types_authorization_inner_response diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.cc index 62030b65fad073394a1463af1c9338245df4c232..1370a75ba1218a20a734105acfdad4fc02d9bc57 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.cc @@ -1,30 +1,30 @@ -#include "etsi_ts102941_types_authorization_shared_at_request.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_authorization_shared_at_request::encode(const EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, - OCTETSTRING & p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_authorization_shared_at_request::encode: %s", p_shared_at_request.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_shared_at_request.encode(*p_shared_at_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_authorization_shared_at_request::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_authorization_shared_at_request::decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_shared_at_request::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_shared_at_request.decode(*p_shared_at_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_shared_at_request::decode: ", (const Base_Type &)p_shared_at_request); - return 0; -} +#include "etsi_ts102941_types_authorization_shared_at_request.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_authorization_shared_at_request::encode(const EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, + OCTETSTRING & p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_authorization_shared_at_request::encode: %s", p_shared_at_request.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_shared_at_request.encode(*p_shared_at_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_authorization_shared_at_request::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_authorization_shared_at_request::decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_shared_at_request::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_shared_at_request.decode(*p_shared_at_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_shared_at_request::decode: ", (const Base_Type &)p_shared_at_request); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.hh index 4ce4b01c1220662c796bae0f8b4bc6143ba103e2..7e8dbad6835dcf15924773ee3dd7be0a415a2342 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_shared_at_request.hh @@ -1,17 +1,17 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesAuthorization.hh" - -class etsi_ts102941_types_authorization_shared_at_request - : public codec { -public: - explicit etsi_ts102941_types_authorization_shared_at_request() - : codec(){}; - virtual ~etsi_ts102941_types_authorization_shared_at_request(){}; - - virtual int encode(const EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, params *p_params = NULL); -}; // End of class etsi_ts102941_types_authorization_shared_at_request +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesAuthorization.hh" + +class etsi_ts102941_types_authorization_shared_at_request + : public codec { +public: + explicit etsi_ts102941_types_authorization_shared_at_request() + : codec(){}; + virtual ~etsi_ts102941_types_authorization_shared_at_request(){}; + + virtual int encode(const EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorization::SharedAtRequest &p_shared_at_request, params *p_params = NULL); +}; // End of class etsi_ts102941_types_authorization_shared_at_request diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.cc index 55e3680bfd2bd1565f73bdd4145eef74ba4dd8e3..accd048f1d9964e12035b2ca1825ae1b1b67b29d 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.cc @@ -1,31 +1,31 @@ -#include "etsi_ts102941_types_authorization_validation_request.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_authorization_validation_request::encode( - const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_authorization_validation_request::encode: %s", - p_authorization_validation_request.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_authorization_validation_request.encode(*p_authorization_validation_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_authorization_validation_request::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_authorization_validation_request::decode( - const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_validation_request::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_authorization_validation_request.decode(*p_authorization_validation_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_validation_request::decode: ", (const Base_Type &)p_authorization_validation_request); - return 0; -} +#include "etsi_ts102941_types_authorization_validation_request.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_authorization_validation_request::encode( + const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_authorization_validation_request::encode: %s", + p_authorization_validation_request.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_authorization_validation_request.encode(*p_authorization_validation_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_authorization_validation_request::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_authorization_validation_request::decode( + const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_validation_request::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_authorization_validation_request.decode(*p_authorization_validation_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_validation_request::decode: ", (const Base_Type &)p_authorization_validation_request); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.hh index 96f59916307e13e8d1a3526ca643d447abd67429..4f545d4fcdd190b0ac28091a9db89cbdfcecbbee 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_request.hh @@ -1,19 +1,19 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesAuthorizationValidation.hh" - -class etsi_ts102941_types_authorization_validation_request : public codec { -public: - explicit etsi_ts102941_types_authorization_validation_request() - : codec(){}; - virtual ~etsi_ts102941_types_authorization_validation_request(){}; - - virtual int encode(const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, - params *p_params = NULL); -}; // End of class etsi_ts102941_types_authorization_validation_request +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesAuthorizationValidation.hh" + +class etsi_ts102941_types_authorization_validation_request : public codec { +public: + explicit etsi_ts102941_types_authorization_validation_request() + : codec(){}; + virtual ~etsi_ts102941_types_authorization_validation_request(){}; + + virtual int encode(const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationRequest &p_authorization_validation_request, + params *p_params = NULL); +}; // End of class etsi_ts102941_types_authorization_validation_request diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.cc index 9d2b8ee223d6d3fe91b00ec74c310e1472887725..168d4d601bac48a9870b5b3fd2840e59e3f2c3c4 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.cc @@ -1,32 +1,32 @@ -#include "etsi_ts102941_types_authorization_validation_response.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_authorization_validation_response::encode( - const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_authorization_validation_response::encode: %s", - p_authorization_validation_response.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_authorization_validation_response.encode(*p_authorization_validation_response.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_authorization_validation_response::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_authorization_validation_response::decode( - const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_validation_response::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_authorization_validation_response.decode(*p_authorization_validation_response.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_validation_response::decode: ", - (const Base_Type &)p_authorization_validation_response); - return 0; -} +#include "etsi_ts102941_types_authorization_validation_response.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_authorization_validation_response::encode( + const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_authorization_validation_response::encode: %s", + p_authorization_validation_response.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_authorization_validation_response.encode(*p_authorization_validation_response.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_authorization_validation_response::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_authorization_validation_response::decode( + const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_authorization_validation_response::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_authorization_validation_response.decode(*p_authorization_validation_response.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_authorization_validation_response::decode: ", + (const Base_Type &)p_authorization_validation_response); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.hh index b43889c7f638e23fe02a9c9bbc0c5fcb06b9f2ab..27f387b43a3928f31068189da9ffa7d342feb103 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_authorization_validation_response.hh @@ -1,19 +1,19 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesAuthorizationValidation.hh" - -class etsi_ts102941_types_authorization_validation_response : public codec { -public: - explicit etsi_ts102941_types_authorization_validation_response() - : codec(){}; - virtual ~etsi_ts102941_types_authorization_validation_response(){}; - - virtual int encode(const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, - params *p_params = NULL); -}; // End of class etsi_ts102941_types_authorization_validation_response +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesAuthorizationValidation.hh" + +class etsi_ts102941_types_authorization_validation_response : public codec { +public: + explicit etsi_ts102941_types_authorization_validation_response() + : codec(){}; + virtual ~etsi_ts102941_types_authorization_validation_response(){}; + + virtual int encode(const EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesAuthorizationValidation::AuthorizationValidationResponse &p_authorization_validation_response, + params *p_params = NULL); +}; // End of class etsi_ts102941_types_authorization_validation_response diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.cc index 18b7b4b1fc8c86ab29b0f18779c97923b15bcb68..a7413993c0d72ff13dcacebf57a270ff70a055b5 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.cc @@ -1,29 +1,29 @@ -#include "etsi_ts102941_types_enrolment_inner_request.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_enrolment_inner_request::encode(const EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_enrolment_inner_request::encode: %s", p_inner_request.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_inner_request.encode(*p_inner_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_enrolment_inner_request::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_enrolment_inner_request::decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_enrolment_inner_request::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_inner_request.decode(*p_inner_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_enrolment_inner_request::decode: ", (const Base_Type &)p_inner_request); - return 0; -} +#include "etsi_ts102941_types_enrolment_inner_request.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_enrolment_inner_request::encode(const EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_enrolment_inner_request::encode: %s", p_inner_request.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_inner_request.encode(*p_inner_request.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_enrolment_inner_request::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_enrolment_inner_request::decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_enrolment_inner_request::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_inner_request.decode(*p_inner_request.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_enrolment_inner_request::decode: ", (const Base_Type &)p_inner_request); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.hh index 2fbb2ac8f3e823772fd4c78b87cfd1c741af8263..8fba3a68739768e968f0754d307aef3f37f0518b 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_request.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesEnrolment.hh" - -class etsi_ts102941_types_enrolment_inner_request : public codec { -public: - explicit etsi_ts102941_types_enrolment_inner_request() : codec(){}; - virtual ~etsi_ts102941_types_enrolment_inner_request(){}; - - virtual int encode(const EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, params *p_params = NULL); -}; // End of class etsi_ts102941_types_enrolment_inner_request +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesEnrolment.hh" + +class etsi_ts102941_types_enrolment_inner_request : public codec { +public: + explicit etsi_ts102941_types_enrolment_inner_request() : codec(){}; + virtual ~etsi_ts102941_types_enrolment_inner_request(){}; + + virtual int encode(const EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcRequest &p_inner_request, params *p_params = NULL); +}; // End of class etsi_ts102941_types_enrolment_inner_request diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.cc b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.cc index 589364db5553efb4271c86082e351826b723af2c..99a1a44f88a9a9e01be7e50d17702f55e64faf6f 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.cc +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.cc @@ -1,29 +1,29 @@ -#include "etsi_ts102941_types_enrolment_inner_response.hh" - -#include "loggers.hh" - -int etsi_ts102941_types_enrolment_inner_response::encode(const EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts102941_types_enrolment_inner_response::encode: %s", p_inner_response.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_inner_response.encode(*p_inner_response.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts102941_types_enrolment_inner_response::encode: ", p_data); - - return 0; -} - -int etsi_ts102941_types_enrolment_inner_response::decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, - params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts102941_types_enrolment_inner_response::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_inner_response.decode(*p_inner_response.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts102941_types_enrolment_inner_response::decode: ", (const Base_Type &)p_inner_response); - return 0; -} +#include "etsi_ts102941_types_enrolment_inner_response.hh" + +#include "loggers.hh" + +int etsi_ts102941_types_enrolment_inner_response::encode(const EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts102941_types_enrolment_inner_response::encode: %s", p_inner_response.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_inner_response.encode(*p_inner_response.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts102941_types_enrolment_inner_response::encode: ", p_data); + + return 0; +} + +int etsi_ts102941_types_enrolment_inner_response::decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, + params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts102941_types_enrolment_inner_response::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_inner_response.decode(*p_inner_response.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts102941_types_enrolment_inner_response::decode: ", (const Base_Type &)p_inner_response); + return 0; +} diff --git a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.hh b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.hh index c4cc72253ef793edb53bc6d534e7785ac4536819..b5e26b2c3bc87dbc1c33107ee1e426150265eb31 100644 --- a/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.hh +++ b/ccsrc/Protocols/Security/etsi_ts102941_types_enrolment_inner_response.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "EtsiTs102941TypesEnrolment.hh" - -class etsi_ts102941_types_enrolment_inner_response : public codec { -public: - explicit etsi_ts102941_types_enrolment_inner_response() : codec(){}; - virtual ~etsi_ts102941_types_enrolment_inner_response(){}; - - virtual int encode(const EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, params *p_params = NULL); -}; // End of class etsi_ts102941_types_enrolment_inner_response +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "EtsiTs102941TypesEnrolment.hh" + +class etsi_ts102941_types_enrolment_inner_response : public codec { +public: + explicit etsi_ts102941_types_enrolment_inner_response() : codec(){}; + virtual ~etsi_ts102941_types_enrolment_inner_response(){}; + + virtual int encode(const EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, EtsiTs102941TypesEnrolment::InnerEcResponse &p_inner_response, params *p_params = NULL); +}; // End of class etsi_ts102941_types_enrolment_inner_response diff --git a/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.cc b/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.cc index e3391b26934287e6867c4a49e76951415bfab7c4..5fc427b69a949488ac8c24ae3fc624678778837a 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.cc +++ b/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.cc @@ -1,46 +1,46 @@ -#include "EtsiTs103097Module.hh" - -#include "asn1/EtsiTs103097Certificate.h" -#include "asn1/asn_application.h" // from asn1c -#include "etsi_ts103097_certificate_codec.hh" - -#include "loggers.hh" - -int etsi_ts103097_certificate_codec::encode(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts103097_certificate_codec::encode: %s", p_cert.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_cert.encode(*p_cert.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts103097_certificate_codec::encode: ", p_data); - - return 0; -} - -int etsi_ts103097_certificate_codec::decode(const OCTETSTRING &p_data, Ieee1609Dot2::CertificateBase &p_cert, params *params) { - loggers::get_instance().log_msg(">>> etsi_ts103097_certificate_codec::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - _params = params; - p_cert.decode(*p_cert.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts103097_certificate_codec::decode: ", (const Base_Type &)p_cert); - return 0; -} - -// extern "C" { -// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; -// } - -// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::CertificateBase& p_cert, BITSTRING& p_p_data) -// { -// return _encode(Ieee1609Dot2::CertificateBase_descr_, asn_DEF_EtsiTs103097Certificate, p_cert, p_p_data); -// } - -// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_p_data, Ieee1609Dot2::CertificateBase& p_cert) -// { -// return _decode(Ieee1609Dot2::CertificateBase_descr_, asn_DEF_EtsiTs103097Certificate, p_p_data, p_cert); -// } +#include "EtsiTs103097Module.hh" + +#include "asn1/EtsiTs103097Certificate.h" +#include "asn1/asn_application.h" // from asn1c +#include "etsi_ts103097_certificate_codec.hh" + +#include "loggers.hh" + +int etsi_ts103097_certificate_codec::encode(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts103097_certificate_codec::encode: %s", p_cert.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_cert.encode(*p_cert.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts103097_certificate_codec::encode: ", p_data); + + return 0; +} + +int etsi_ts103097_certificate_codec::decode(const OCTETSTRING &p_data, Ieee1609Dot2::CertificateBase &p_cert, params *params) { + loggers::get_instance().log_msg(">>> etsi_ts103097_certificate_codec::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + _params = params; + p_cert.decode(*p_cert.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts103097_certificate_codec::decode: ", (const Base_Type &)p_cert); + return 0; +} + +// extern "C" { +// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; +// } + +// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::CertificateBase& p_cert, BITSTRING& p_p_data) +// { +// return _encode(Ieee1609Dot2::CertificateBase_descr_, asn_DEF_EtsiTs103097Certificate, p_cert, p_p_data); +// } + +// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_p_data, Ieee1609Dot2::CertificateBase& p_cert) +// { +// return _decode(Ieee1609Dot2::CertificateBase_descr_, asn_DEF_EtsiTs103097Certificate, p_p_data, p_cert); +// } diff --git a/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.hh b/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.hh index 0257f1c4b03619364d82a9e22ac7b48c4842de36..707aa240950258af99388625f82c9814ab3a7eb2 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.hh +++ b/ccsrc/Protocols/Security/etsi_ts103097_certificate_codec.hh @@ -1,30 +1,30 @@ -#pragma once - -#include "codec.hh" -//#include "oer_codec.hh" -#include "params.hh" - -#include "EtsiTs103097Module.hh" -// class BITSTRING; -// class OCTETSTRING; -// class Ieee1609Dot2::CertificateBase; - -// class EtsiTs103097PDUCodec// : public oer_codec -// { -// public: -// explicit EtsiTs103097PDUCodec() { }; -// virtual int encode (const Ieee1609Dot2::CertificateBase& p_cert, BITSTRING& data); -// virtual int decode (const BITSTRING& data, Ieee1609Dot2::CertificateBase&); -// }; - -class etsi_ts103097_certificate_codec : public codec { - // EtsiTs103097PDUCodec asn_codec; - -public: - // explicit etsi_ts103097_certificate_codec() : codec(), asn_codec() { }; - explicit etsi_ts103097_certificate_codec() : codec(){}; - virtual ~etsi_ts103097_certificate_codec(){}; - - virtual int encode(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::CertificateBase &p_cert, params *p_params = NULL); -}; // End of class etsi_ts103097_certificate_codec +#pragma once + +#include "codec.hh" +//#include "oer_codec.hh" +#include "params.hh" + +#include "EtsiTs103097Module.hh" +// class BITSTRING; +// class OCTETSTRING; +// class Ieee1609Dot2::CertificateBase; + +// class EtsiTs103097PDUCodec// : public oer_codec +// { +// public: +// explicit EtsiTs103097PDUCodec() { }; +// virtual int encode (const Ieee1609Dot2::CertificateBase& p_cert, BITSTRING& data); +// virtual int decode (const BITSTRING& data, Ieee1609Dot2::CertificateBase&); +// }; + +class etsi_ts103097_certificate_codec : public codec { + // EtsiTs103097PDUCodec asn_codec; + +public: + // explicit etsi_ts103097_certificate_codec() : codec(), asn_codec() { }; + explicit etsi_ts103097_certificate_codec() : codec(){}; + virtual ~etsi_ts103097_certificate_codec(){}; + + virtual int encode(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::CertificateBase &p_cert, params *p_params = NULL); +}; // End of class etsi_ts103097_certificate_codec diff --git a/ccsrc/Protocols/Security/etsi_ts103097_data_codec.cc b/ccsrc/Protocols/Security/etsi_ts103097_data_codec.cc index 2617bda080a44919c55df9ce9e1e8378e1496bde..18e045de33fdc84a86729e92ada62909421a5fa4 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_data_codec.cc +++ b/ccsrc/Protocols/Security/etsi_ts103097_data_codec.cc @@ -1,46 +1,46 @@ -#include "EtsiTs103097Module.hh" - -#include "asn1/EtsiTs103097Certificate.h" -#include "asn1/asn_application.h" // from asn1c -#include "etsi_ts103097_data_codec.hh" - -#include "loggers.hh" - -int etsi_ts103097_data_codec::encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> etsi_ts103097_data_codec::encode: %s", p_ieee1609Dot2Data.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_ieee1609Dot2Data.encode(*p_ieee1609Dot2Data.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts103097_data_codec::encode: ", p_data); - - return 0; -} - -int etsi_ts103097_data_codec::decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, params *p_params) { - loggers::get_instance().log_msg(">>> etsi_ts103097_data_codec::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - _params = p_params; - p_ieee1609Dot2Data.decode(*p_ieee1609Dot2Data.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts103097_data_codec::decode: ", (const Base_Type &)p_ieee1609Dot2Data); - return 0; -} - -// extern "C" { -// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; -// } - -// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::Ieee1609Dot2Data& p_cert, BITSTRING& p_data) -// { -// return _encode(Ieee1609Dot2::Ieee1609Dot2Data_descr_, asn_DEF_EtsiTs103097Certificate, p_cert, p_data); -// } - -// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_data, Ieee1609Dot2::Ieee1609Dot2Data& p_cert) -// { -// return _decode(Ieee1609Dot2::Ieee1609Dot2Data_descr_, asn_DEF_EtsiTs103097Certificate, p_data, p_cert); -// } +#include "EtsiTs103097Module.hh" + +#include "asn1/EtsiTs103097Certificate.h" +#include "asn1/asn_application.h" // from asn1c +#include "etsi_ts103097_data_codec.hh" + +#include "loggers.hh" + +int etsi_ts103097_data_codec::encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> etsi_ts103097_data_codec::encode: %s", p_ieee1609Dot2Data.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_ieee1609Dot2Data.encode(*p_ieee1609Dot2Data.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts103097_data_codec::encode: ", p_data); + + return 0; +} + +int etsi_ts103097_data_codec::decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, params *p_params) { + loggers::get_instance().log_msg(">>> etsi_ts103097_data_codec::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + _params = p_params; + p_ieee1609Dot2Data.decode(*p_ieee1609Dot2Data.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts103097_data_codec::decode: ", (const Base_Type &)p_ieee1609Dot2Data); + return 0; +} + +// extern "C" { +// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; +// } + +// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::Ieee1609Dot2Data& p_cert, BITSTRING& p_data) +// { +// return _encode(Ieee1609Dot2::Ieee1609Dot2Data_descr_, asn_DEF_EtsiTs103097Certificate, p_cert, p_data); +// } + +// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_data, Ieee1609Dot2::Ieee1609Dot2Data& p_cert) +// { +// return _decode(Ieee1609Dot2::Ieee1609Dot2Data_descr_, asn_DEF_EtsiTs103097Certificate, p_data, p_cert); +// } diff --git a/ccsrc/Protocols/Security/etsi_ts103097_data_codec.hh b/ccsrc/Protocols/Security/etsi_ts103097_data_codec.hh index 6cb783d934d3b93c4483142cc086f6bff6bb7597..f42e100234568f98fd3d5e27afaf21077e8a0bbd 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_data_codec.hh +++ b/ccsrc/Protocols/Security/etsi_ts103097_data_codec.hh @@ -1,30 +1,30 @@ -#pragma once - -#include "codec.hh" -//#include "CodecOer.hh" -#include "params.hh" - -#include "EtsiTs103097Module.hh" -// class BITSTRING; -// class OCTETSTRING; -// class Ieee1609Dot2::Ieee1609Dot2Data; - -// class EtsiTs103097PDUCodec// : public oer_codec -// { -// public: -// explicit EtsiTs103097PDUCodec() { }; -// virtual int encode (const Ieee1609Dot2::Ieee1609Dot2Data& p_cert, BITSTRING& data); -// virtual int decode (const BITSTRING& data, Ieee1609Dot2::Ieee1609Dot2Data&); -// }; - -class etsi_ts103097_data_codec : public codec { - // EtsiTs103097PDUCodec asn_codec; - -public: - // explicit etsi_ts103097_data_codec() : codec(), asn_codec() { }; - explicit etsi_ts103097_data_codec() : codec(){}; - virtual ~etsi_ts103097_data_codec(){}; - - virtual int encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, params *params = NULL); -}; +#pragma once + +#include "codec.hh" +//#include "CodecOer.hh" +#include "params.hh" + +#include "EtsiTs103097Module.hh" +// class BITSTRING; +// class OCTETSTRING; +// class Ieee1609Dot2::Ieee1609Dot2Data; + +// class EtsiTs103097PDUCodec// : public oer_codec +// { +// public: +// explicit EtsiTs103097PDUCodec() { }; +// virtual int encode (const Ieee1609Dot2::Ieee1609Dot2Data& p_cert, BITSTRING& data); +// virtual int decode (const BITSTRING& data, Ieee1609Dot2::Ieee1609Dot2Data&); +// }; + +class etsi_ts103097_data_codec : public codec { + // EtsiTs103097PDUCodec asn_codec; + +public: + // explicit etsi_ts103097_data_codec() : codec(), asn_codec() { }; + explicit etsi_ts103097_data_codec() : codec(){}; + virtual ~etsi_ts103097_data_codec(){}; + + virtual int encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee1609Dot2Data, params *params = NULL); +}; diff --git a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.cc b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.cc index 4d2c2c2757a27c4bc8555a7f956e3f0a6147623e..ab032fbd54c9f85c540db8542921908d858a49be 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.cc +++ b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.cc @@ -1,46 +1,46 @@ -#include "EtsiTs103097Module.hh" - -#include "asn1/EtsiTs103097Certificate.h" -#include "asn1/asn_application.h" // from asn1c -#include "etsi_ts103097_tobesigned_certificate_codec.hh" - -#include "loggers.hh" - -int etsi_ts103097_tobesigned_certificate_codec::encode(const Ieee1609Dot2::ToBeSignedCertificate &p_cert, OCTETSTRING &data) { - loggers::get_instance().log(">>> etsi_ts103097_tobesigned_certificate_codec::encode: %s", p_cert.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_cert.encode(*p_cert.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts103097_tobesigned_certificate_codec::encode: ", data); - - return 0; -} - -int etsi_ts103097_tobesigned_certificate_codec::decode(const OCTETSTRING &data, Ieee1609Dot2::ToBeSignedCertificate &p_cert, params *params) { - loggers::get_instance().log_msg(">>> etsi_ts103097_tobesigned_certificate_codec::decode: ", data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - p_cert.decode(*p_cert.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts103097_tobesigned_certificate_codec::decode: ", (const Base_Type &)p_cert); - return 0; -} - -// extern "C" { -// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; -// } - -// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::ToBeSignedCertificate& p_cert, BITSTRING& p_data) -// { -// return _encode(Ieee1609Dot2::ToBeSignedCertificate_descr_, asn_DEF_EtsiTs103097Certificate, p_cert, p_data); -// } - -// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_data, Ieee1609Dot2::ToBeSignedCertificate& p_cert) -// { -// return _decode(Ieee1609Dot2::ToBeSignedCertificate_descr_, asn_DEF_EtsiTs103097Certificate, p_data, p_cert); -// } +#include "EtsiTs103097Module.hh" + +#include "asn1/EtsiTs103097Certificate.h" +#include "asn1/asn_application.h" // from asn1c +#include "etsi_ts103097_tobesigned_certificate_codec.hh" + +#include "loggers.hh" + +int etsi_ts103097_tobesigned_certificate_codec::encode(const Ieee1609Dot2::ToBeSignedCertificate &p_cert, OCTETSTRING &data) { + loggers::get_instance().log(">>> etsi_ts103097_tobesigned_certificate_codec::encode: %s", p_cert.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_cert.encode(*p_cert.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts103097_tobesigned_certificate_codec::encode: ", data); + + return 0; +} + +int etsi_ts103097_tobesigned_certificate_codec::decode(const OCTETSTRING &data, Ieee1609Dot2::ToBeSignedCertificate &p_cert, params *params) { + loggers::get_instance().log_msg(">>> etsi_ts103097_tobesigned_certificate_codec::decode: ", data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + p_cert.decode(*p_cert.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts103097_tobesigned_certificate_codec::decode: ", (const Base_Type &)p_cert); + return 0; +} + +// extern "C" { +// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; +// } + +// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::ToBeSignedCertificate& p_cert, BITSTRING& p_data) +// { +// return _encode(Ieee1609Dot2::ToBeSignedCertificate_descr_, asn_DEF_EtsiTs103097Certificate, p_cert, p_data); +// } + +// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_data, Ieee1609Dot2::ToBeSignedCertificate& p_cert) +// { +// return _decode(Ieee1609Dot2::ToBeSignedCertificate_descr_, asn_DEF_EtsiTs103097Certificate, p_data, p_cert); +// } diff --git a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.hh b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.hh index 5bb9cb0d48028da7faaa7a84dff3a91520951862..7d93849983509c313d1684b43cd8b2e4035a1b76 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.hh +++ b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_certificate_codec.hh @@ -1,30 +1,30 @@ -#pragma once - -#include "codec.hh" -//#include "CodecOer.hh" -#include "params.hh" - -#include "EtsiTs103097Module.hh" -// class BITSTRING; -// class OCTETSTRING; -// class Ieee1609Dot2::ToBeSignedCertificate; - -// class EtsiTs103097PDUCodec// : public oer_codec -// { -// public: -// explicit EtsiTs103097PDUCodec() { }; -// virtual int encode (const Ieee1609Dot2::ToBeSignedCertificate& p_cert, BITSTRING& data); -// virtual int decode (const BITSTRING& data, Ieee1609Dot2::ToBeSignedCertificate&); -// }; - -class etsi_ts103097_tobesigned_certificate_codec : public codec { - // EtsiTs103097PDUCodec asn_codec; - -public: - // explicit etsi_ts103097_tobesigned_certificate_codec() : codec(), asn_codec() { }; - explicit etsi_ts103097_tobesigned_certificate_codec() : codec(){}; - virtual ~etsi_ts103097_tobesigned_certificate_codec(){}; - - virtual int encode(const Ieee1609Dot2::ToBeSignedCertificate &p_cert, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::ToBeSignedCertificate &p_cert, params *p_params = NULL); -}; +#pragma once + +#include "codec.hh" +//#include "CodecOer.hh" +#include "params.hh" + +#include "EtsiTs103097Module.hh" +// class BITSTRING; +// class OCTETSTRING; +// class Ieee1609Dot2::ToBeSignedCertificate; + +// class EtsiTs103097PDUCodec// : public oer_codec +// { +// public: +// explicit EtsiTs103097PDUCodec() { }; +// virtual int encode (const Ieee1609Dot2::ToBeSignedCertificate& p_cert, BITSTRING& data); +// virtual int decode (const BITSTRING& data, Ieee1609Dot2::ToBeSignedCertificate&); +// }; + +class etsi_ts103097_tobesigned_certificate_codec : public codec { + // EtsiTs103097PDUCodec asn_codec; + +public: + // explicit etsi_ts103097_tobesigned_certificate_codec() : codec(), asn_codec() { }; + explicit etsi_ts103097_tobesigned_certificate_codec() : codec(){}; + virtual ~etsi_ts103097_tobesigned_certificate_codec(){}; + + virtual int encode(const Ieee1609Dot2::ToBeSignedCertificate &p_cert, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::ToBeSignedCertificate &p_cert, params *p_params = NULL); +}; diff --git a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.cc b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.cc index 00690812738b2e08b728c19a24abc8eec86be63a..de882c8ac5858554e0cd92263cd85176875708d4 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.cc +++ b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.cc @@ -1,46 +1,46 @@ -#include "EtsiTs103097Module.hh" - -#include "asn1/EtsiTs103097Data.h" -#include "asn1/asn_application.h" // from asn1c -#include "etsi_ts103097_tobesigned_data_codec.hh" - -#include "loggers.hh" - -int etsi_ts103097_tobesigned_data_codec::encode(const Ieee1609Dot2::ToBeSignedData &p_cert, OCTETSTRING &data) { - loggers::get_instance().log(">>> etsi_ts103097_tobesigned_data_codec::encode: %s", p_cert.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_cert.encode(*p_cert.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("etsi_ts103097_tobesigned_data_codec::encode: ", data); - - return 0; -} - -int etsi_ts103097_tobesigned_data_codec::decode(const OCTETSTRING &data, Ieee1609Dot2::ToBeSignedData &p_cert, params *params) { - loggers::get_instance().log_msg(">>> etsi_ts103097_tobesigned_data_codec::decode: ", data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - p_cert.decode(*p_cert.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< etsi_ts103097_tobesigned_data_codec::decode: ", (const Base_Type &)p_cert); - return 0; -} - -// extern "C" { -// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; -// } - -// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::ToBeSignedData& p_cert, BITSTRING& p_data) -// { -// return _encode(Ieee1609Dot2::ToBeSignedData_descr_, asn_DEF_EtsiTs103097Data, p_cert, p_data); -// } - -// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_data, Ieee1609Dot2::ToBeSignedData& p_cert) -// { -// return _decode(Ieee1609Dot2::ToBeSignedData_descr_, asn_DEF_EtsiTs103097Data, p_data, p_cert); -// } +#include "EtsiTs103097Module.hh" + +#include "asn1/EtsiTs103097Data.h" +#include "asn1/asn_application.h" // from asn1c +#include "etsi_ts103097_tobesigned_data_codec.hh" + +#include "loggers.hh" + +int etsi_ts103097_tobesigned_data_codec::encode(const Ieee1609Dot2::ToBeSignedData &p_cert, OCTETSTRING &data) { + loggers::get_instance().log(">>> etsi_ts103097_tobesigned_data_codec::encode: %s", p_cert.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_cert.encode(*p_cert.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("etsi_ts103097_tobesigned_data_codec::encode: ", data); + + return 0; +} + +int etsi_ts103097_tobesigned_data_codec::decode(const OCTETSTRING &data, Ieee1609Dot2::ToBeSignedData &p_cert, params *params) { + loggers::get_instance().log_msg(">>> etsi_ts103097_tobesigned_data_codec::decode: ", data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + p_cert.decode(*p_cert.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< etsi_ts103097_tobesigned_data_codec::decode: ", (const Base_Type &)p_cert); + return 0; +} + +// extern "C" { +// extern asn_TYPE_descriptor_t asn_DEF_EtsiTs103097; +// } + +// int EtsiTs103097PDUCodec::encode (const Ieee1609Dot2::ToBeSignedData& p_cert, BITSTRING& p_data) +// { +// return _encode(Ieee1609Dot2::ToBeSignedData_descr_, asn_DEF_EtsiTs103097Data, p_cert, p_data); +// } + +// int EtsiTs103097PDUCodec::decode (const BITSTRING& p_data, Ieee1609Dot2::ToBeSignedData& p_cert) +// { +// return _decode(Ieee1609Dot2::ToBeSignedData_descr_, asn_DEF_EtsiTs103097Data, p_data, p_cert); +// } diff --git a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.hh b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.hh index 95f0b54ca6022db48bbb86a90ce21cbd211b9062..6e0b4a834478fb79af866fc6eda9da7a0674de87 100644 --- a/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.hh +++ b/ccsrc/Protocols/Security/etsi_ts103097_tobesigned_data_codec.hh @@ -1,30 +1,30 @@ -#pragma once - -#include "codec.hh" -//#include "CodecOer.hh" -#include "params.hh" - -#include "EtsiTs103097Module.hh" -// class BITSTRING; -// class OCTETSTRING; -// class Ieee1609Dot2::ToBeSignedData; - -// class EtsiTs103097PDUCodec// : public oer_codec -// { -// public: -// explicit EtsiTs103097PDUCodec() { }; -// virtual int encode (const Ieee1609Dot2::ToBeSignedData& p_cert, BITSTRING& data); -// virtual int decode (const BITSTRING& data, Ieee1609Dot2::ToBeSignedData&); -// }; - -class etsi_ts103097_tobesigned_data_codec : public codec { - // EtsiTs103097PDUCodec asn_codec; - -public: - // explicit etsi_ts103097_tobesigned_data_codec() : codec(), asn_codec() { }; - explicit etsi_ts103097_tobesigned_data_codec() : codec(){}; - virtual ~etsi_ts103097_tobesigned_data_codec(){}; - - virtual int encode(const Ieee1609Dot2::ToBeSignedData &p_cert, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::ToBeSignedData &p_cert, params *p_params = NULL); -}; +#pragma once + +#include "codec.hh" +//#include "CodecOer.hh" +#include "params.hh" + +#include "EtsiTs103097Module.hh" +// class BITSTRING; +// class OCTETSTRING; +// class Ieee1609Dot2::ToBeSignedData; + +// class EtsiTs103097PDUCodec// : public oer_codec +// { +// public: +// explicit EtsiTs103097PDUCodec() { }; +// virtual int encode (const Ieee1609Dot2::ToBeSignedData& p_cert, BITSTRING& data); +// virtual int decode (const BITSTRING& data, Ieee1609Dot2::ToBeSignedData&); +// }; + +class etsi_ts103097_tobesigned_data_codec : public codec { + // EtsiTs103097PDUCodec asn_codec; + +public: + // explicit etsi_ts103097_tobesigned_data_codec() : codec(), asn_codec() { }; + explicit etsi_ts103097_tobesigned_data_codec() : codec(){}; + virtual ~etsi_ts103097_tobesigned_data_codec(){}; + + virtual int encode(const Ieee1609Dot2::ToBeSignedData &p_cert, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::ToBeSignedData &p_cert, params *p_params = NULL); +}; diff --git a/ccsrc/Protocols/Security/hmac.cc b/ccsrc/Protocols/Security/hmac.cc index eff6cd4dc94ddce104ebca98e7bf94ab8a7a0ec9..0ff752057113ca01e07f3ad4e780c9b8ce9d32ed 100644 --- a/ccsrc/Protocols/Security/hmac.cc +++ b/ccsrc/Protocols/Security/hmac.cc @@ -1,54 +1,54 @@ -/*! - * \file hmac.cc - * \brief Source file for HMAC helper methods. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include - -#include "hmac.hh" - -#include "loggers.hh" - -int hmac::generate(const OCTETSTRING p_buffer, const OCTETSTRING p_secret_key, OCTETSTRING &p_hmac) { - // Sanity check - if (p_buffer.lengthof() == 0) { - return -1; - } - - return generate(static_cast(p_buffer), p_buffer.lengthof(), static_cast(p_secret_key), p_secret_key.lengthof(), - p_hmac); -} - -int hmac::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) { - // Sanity check - if ((p_buffer == nullptr) || (p_secret_key == nullptr)) { - return -1; - } - ::HMAC_CTX_reset(_ctx); - - p_hmac = int2oct(0, EVP_MAX_MD_SIZE); - if (_hash_algorithms == hash_algorithms::sha_256) { - ::HMAC_Init_ex(_ctx, (const void *)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha256(), NULL); - } else if (_hash_algorithms == hash_algorithms::sha_384) { - ::HMAC_Init_ex(_ctx, (const void *)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha384(), NULL); - } else { // TODO To be continued - return -1; - } - // Compute the hash value - ::HMAC_Update(_ctx, p_buffer, p_buffer_length); - unsigned int length = p_hmac.lengthof(); - ::HMAC_Final(_ctx, (unsigned char *)static_cast(p_hmac), &length); - loggers::get_instance().log_to_hexa("hmac::generate: ", (unsigned char *)static_cast(p_hmac), length); - // Resize the hmac - if (_hash_algorithms == hash_algorithms::sha_256) { - p_hmac = OCTETSTRING(16, static_cast(p_hmac)); - } // FIXME Check length for the other hash algorithm - - return 0; -} +/*! + * \file hmac.cc + * \brief Source file for HMAC helper methods. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include + +#include "hmac.hh" + +#include "loggers.hh" + +int hmac::generate(const OCTETSTRING p_buffer, const OCTETSTRING p_secret_key, OCTETSTRING &p_hmac) { + // Sanity check + if (p_buffer.lengthof() == 0) { + return -1; + } + + return generate(static_cast(p_buffer), p_buffer.lengthof(), static_cast(p_secret_key), p_secret_key.lengthof(), + p_hmac); +} + +int hmac::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) { + // Sanity check + if ((p_buffer == nullptr) || (p_secret_key == nullptr)) { + return -1; + } + ::HMAC_CTX_reset(_ctx); + + p_hmac = int2oct(0, EVP_MAX_MD_SIZE); + if (_hash_algorithms == hash_algorithms::sha_256) { + ::HMAC_Init_ex(_ctx, (const void *)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha256(), NULL); + } else if (_hash_algorithms == hash_algorithms::sha_384) { + ::HMAC_Init_ex(_ctx, (const void *)p_secret_key, (long unsigned int)p_secret_key_length, EVP_sha384(), NULL); + } else { // TODO To be continued + return -1; + } + // Compute the hash value + ::HMAC_Update(_ctx, p_buffer, p_buffer_length); + unsigned int length = p_hmac.lengthof(); + ::HMAC_Final(_ctx, (unsigned char *)static_cast(p_hmac), &length); + loggers::get_instance().log_to_hexa("hmac::generate: ", (unsigned char *)static_cast(p_hmac), length); + // Resize the hmac + if (_hash_algorithms == hash_algorithms::sha_256) { + p_hmac = OCTETSTRING(16, static_cast(p_hmac)); + } // FIXME Check length for the other hash algorithm + + return 0; +} diff --git a/ccsrc/Protocols/Security/hmac.hh b/ccsrc/Protocols/Security/hmac.hh index ec245471c252ca5e60ac6ca16f7da3fcb7541bcd..9ae7215bd1729c2d75f6a722eb4d95f2f01a7d46 100644 --- a/ccsrc/Protocols/Security/hmac.hh +++ b/ccsrc/Protocols/Security/hmac.hh @@ -1,69 +1,69 @@ -/*! - * \file hmac.hh - * \brief Header file for HMAC helper methods. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include - -class OCTETSTRING; //! TITAN forward declaration - -/*! - * \enum Supported hash algorithms - */ -enum class hash_algorithms : unsigned char { - sha_256, /*!< HMAC with SHA-256 */ - sha_384 /*!< HMAC with SHA-384 */ -}; // End of class hash_algorithms - -/*! - * \class hmac - * \brief This class provides description of HMAC helper methods - */ -class hmac { - HMAC_CTX * _ctx; //! HMAC context - hash_algorithms _hash_algorithms; //! HMAC hash algorithm to use -public: - /*! - * \brief Default constructor - * Create a new instance of the hmac class - * \param[in] p_hash_algorithms The hash algorithm to be used to compute the HMAC. Default: sha_256 - */ - hmac(const hash_algorithms p_hash_algorithms = hash_algorithms::sha_256) : _ctx{::HMAC_CTX_new()}, _hash_algorithms(p_hash_algorithms){}; - /*! - * \brief Default destructor - */ - virtual ~hmac() { - if (_ctx != nullptr) { - ::HMAC_CTX_free(_ctx); - }; - }; - - /*! - * \fn int generate(const OCTETSTRING p_buffer, const OCTETSTRING p_secret_key, OCTETSTRING& p_hmac); - * \brief Generate the HMAC of data using a secret key - * \Param[in] p_buffer The data tobe hashed - * \param[in] p_secret_key The secret key to be used to generate the HMAC - * \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); // 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); \brief Generate the HMAC of data using a secret key \param[in] p_buffer The data to be hashed \param[in] p_buffer_length The size of - * the data \param[in] p_secret_key The secret key to be used to generate the HMAC \param[in] p_secret_key_length The size of the secret key \param[out] - * p_hmac The HMAC value based of the provided data \return 0 on success, -1 otherwise - */ - 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); - -}; // End of class hmac +/*! + * \file hmac.hh + * \brief Header file for HMAC helper methods. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include + +class OCTETSTRING; //! TITAN forward declaration + +/*! + * \enum Supported hash algorithms + */ +enum class hash_algorithms : unsigned char { + sha_256, /*!< HMAC with SHA-256 */ + sha_384 /*!< HMAC with SHA-384 */ +}; // End of class hash_algorithms + +/*! + * \class hmac + * \brief This class provides description of HMAC helper methods + */ +class hmac { + HMAC_CTX * _ctx; //! HMAC context + hash_algorithms _hash_algorithms; //! HMAC hash algorithm to use +public: + /*! + * \brief Default constructor + * Create a new instance of the hmac class + * \param[in] p_hash_algorithms The hash algorithm to be used to compute the HMAC. Default: sha_256 + */ + hmac(const hash_algorithms p_hash_algorithms = hash_algorithms::sha_256) : _ctx{::HMAC_CTX_new()}, _hash_algorithms(p_hash_algorithms){}; + /*! + * \brief Default destructor + */ + virtual ~hmac() { + if (_ctx != nullptr) { + ::HMAC_CTX_free(_ctx); + }; + }; + + /*! + * \fn int generate(const OCTETSTRING p_buffer, const OCTETSTRING p_secret_key, OCTETSTRING& p_hmac); + * \brief Generate the HMAC of data using a secret key + * \Param[in] p_buffer The data tobe hashed + * \param[in] p_secret_key The secret key to be used to generate the HMAC + * \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); // 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); \brief Generate the HMAC of data using a secret key \param[in] p_buffer The data to be hashed \param[in] p_buffer_length The size of + * the data \param[in] p_secret_key The secret key to be used to generate the HMAC \param[in] p_secret_key_length The size of the secret key \param[out] + * p_hmac The HMAC value based of the provided data \return 0 on success, -1 otherwise + */ + 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); + +}; // End of class hmac diff --git a/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.cc b/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.cc index 0df131fc025e46eafc4a17ec7251a2ce5bc2be81..94c2c435abcb4432ac636f4d8184cf546731718e 100644 --- a/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.cc +++ b/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.cc @@ -1,36 +1,36 @@ -#include "EtsiTs103097Module.hh" - -#include "http_etsi_ieee1609dot2_codec_factory.hh" - -#include "LibItsHttp_MessageBodyTypes.hh" - -#include "security_services.hh" - -#include "loggers.hh" - -int http_etsi_ieee1609dot2_codec::encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, OCTETSTRING &p_data) { - loggers::get_instance().log_msg(">>> http_etsi_ieee1609dot2_codec::encode: ", p_ieee_1609dot2_data); - - // Encode the Ieee1609Dot2Data - if (_codec.encode(p_ieee_1609dot2_data, p_data) == -1) { - loggers::get_instance().warning("http_etsi_ieee1609dot2_codec::encode: Failed to encode InnerEcRequest"); - return -1; - } - - loggers::get_instance().log_msg("<<< http_etsi_ieee1609dot2_codec::encode: ", p_data); - return 0; -} - -int http_etsi_ieee1609dot2_codec::decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, params *p_params) { - loggers::get_instance().log_msg(">>> http_etsi_ieee1609dot2_codec::decode: ", p_data); - - if (_codec.decode(p_data, p_ieee_1609dot2_data, p_params) == -1) { - loggers::get_instance().warning("http_etsi_ieee1609dot2_codec::decode: Failed to decode data"); - return -1; - } - - loggers::get_instance().log_msg("<<< http_etsi_ieee1609dot2_codec::decode: ", p_ieee_1609dot2_data); - return 0; -} - -http_etsi_ieee1609dot2_codec_factory http_etsi_ieee1609dot2_codec_factory::_f; +#include "EtsiTs103097Module.hh" + +#include "http_etsi_ieee1609dot2_codec_factory.hh" + +#include "LibItsHttp_MessageBodyTypes.hh" + +#include "security_services.hh" + +#include "loggers.hh" + +int http_etsi_ieee1609dot2_codec::encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, OCTETSTRING &p_data) { + loggers::get_instance().log_msg(">>> http_etsi_ieee1609dot2_codec::encode: ", p_ieee_1609dot2_data); + + // Encode the Ieee1609Dot2Data + if (_codec.encode(p_ieee_1609dot2_data, p_data) == -1) { + loggers::get_instance().warning("http_etsi_ieee1609dot2_codec::encode: Failed to encode InnerEcRequest"); + return -1; + } + + loggers::get_instance().log_msg("<<< http_etsi_ieee1609dot2_codec::encode: ", p_data); + return 0; +} + +int http_etsi_ieee1609dot2_codec::decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, params *p_params) { + loggers::get_instance().log_msg(">>> http_etsi_ieee1609dot2_codec::decode: ", p_data); + + if (_codec.decode(p_data, p_ieee_1609dot2_data, p_params) == -1) { + loggers::get_instance().warning("http_etsi_ieee1609dot2_codec::decode: Failed to decode data"); + return -1; + } + + loggers::get_instance().log_msg("<<< http_etsi_ieee1609dot2_codec::decode: ", p_ieee_1609dot2_data); + return 0; +} + +http_etsi_ieee1609dot2_codec_factory http_etsi_ieee1609dot2_codec_factory::_f; diff --git a/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.hh b/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.hh index b91142c8273fd6304a4e7c75e1762de06840584e..3cd3bb3c5c3954c7cc7bf3a33f0405aad9b127d2 100644 --- a/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.hh +++ b/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec.hh @@ -1,20 +1,20 @@ -#pragma once - -#include "etsi_ts103097_data_codec.hh" - -#include "params.hh" - -namespace LibItsHttp__BinaryMessageBodyTypes { - class BinaryBody; -} - -class http_etsi_ieee1609dot2_codec : public codec { - etsi_ts103097_data_codec _codec; - -public: - explicit http_etsi_ieee1609dot2_codec() : codec(), _codec(){}; - virtual ~http_etsi_ieee1609dot2_codec(){}; - - virtual int encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, params *params = NULL); -}; +#pragma once + +#include "etsi_ts103097_data_codec.hh" + +#include "params.hh" + +namespace LibItsHttp__BinaryMessageBodyTypes { + class BinaryBody; +} + +class http_etsi_ieee1609dot2_codec : public codec { + etsi_ts103097_data_codec _codec; + +public: + explicit http_etsi_ieee1609dot2_codec() : codec(), _codec(){}; + virtual ~http_etsi_ieee1609dot2_codec(){}; + + virtual int encode(const Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, params *params = NULL); +}; diff --git a/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec_factory.hh b/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec_factory.hh index 26b7aed620c26fb5ad67cfa0c252f0a4a60a1082..4ef48043c54ef206dd845f5d721dcf4548094340 100644 --- a/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec_factory.hh +++ b/ccsrc/Protocols/Security/http_etsi_ieee1609dot2_codec_factory.hh @@ -1,44 +1,44 @@ -/*! - * \file http_etsi_ieee1609dot2_codec_factory.hh - * \brief Header file for ITS over HTTP protocols codec factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "codec_stack_builder.hh" - -#include "http_etsi_ieee1609dot2_codec.hh" - -class Record_Type; //! TITAN forward declaration - -/*! - * \class http_etsi_ieee1609dot2_codec_factory - * \brief This class provides a factory class to create an http_etsi_ieee1609dot2_codec class instance - */ -class http_etsi_ieee1609dot2_codec_factory : public codec_factory { - static http_etsi_ieee1609dot2_codec_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the http_etsi_ieee1609dot2_codec_factory class - * \remark The HELD/IP codec identifier is HELD - */ - http_etsi_ieee1609dot2_codec_factory() { - // register factory - codec_stack_builder::register_codec_factory("http_etsi_ieee1609dot2_codec", this); - }; - /*! - * \fn codec* create_codec(const std::string & type, const std::string & param); - * \brief Create the codecs stack based on the provided codecs stack description - * \param[in] p_type The provided codecs stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual codec *create_codec() { return (codec *)new http_etsi_ieee1609dot2_codec(); }; -}; // End of class http_etsi_ieee1609dot2_codec_factory +/*! + * \file http_etsi_ieee1609dot2_codec_factory.hh + * \brief Header file for ITS over HTTP protocols codec factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "codec_stack_builder.hh" + +#include "http_etsi_ieee1609dot2_codec.hh" + +class Record_Type; //! TITAN forward declaration + +/*! + * \class http_etsi_ieee1609dot2_codec_factory + * \brief This class provides a factory class to create an http_etsi_ieee1609dot2_codec class instance + */ +class http_etsi_ieee1609dot2_codec_factory : public codec_factory { + static http_etsi_ieee1609dot2_codec_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the http_etsi_ieee1609dot2_codec_factory class + * \remark The HELD/IP codec identifier is HELD + */ + http_etsi_ieee1609dot2_codec_factory() { + // register factory + codec_stack_builder::register_codec_factory("http_etsi_ieee1609dot2_codec", this); + }; + /*! + * \fn codec* create_codec(const std::string & type, const std::string & param); + * \brief Create the codecs stack based on the provided codecs stack description + * \param[in] p_type The provided codecs stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual codec *create_codec() { return (codec *)new http_etsi_ieee1609dot2_codec(); }; +}; // End of class http_etsi_ieee1609dot2_codec_factory diff --git a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.cc b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.cc index 27458ffb661616f79a756391326b84d1817c1355..5732b4f796388fa0b87b1cbfe24a01fa4b042b9e 100644 --- a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.cc +++ b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.cc @@ -1,29 +1,29 @@ -#include "ieee_1609dot2_base_types_public_encryption_key.hh" - -#include "loggers.hh" - -int ieee_1609dot2_base_types_public_encryption_key::encode(const Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, OCTETSTRING &p_data) { - loggers::get_instance().log(">>> ieee_1609dot2_base_types_public_encryption_key::encode: %s", p_public_encryption_key.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_public_encryption_key.encode(*p_public_encryption_key.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("ieee_1609dot2_base_types_public_encryption_key::encode: ", p_data); - - return 0; -} - -int ieee_1609dot2_base_types_public_encryption_key::decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, - params *p_params) { - loggers::get_instance().log_msg(">>> ieee_1609dot2_base_types_public_encryption_key::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_public_encryption_key.decode(*p_public_encryption_key.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< ieee_1609dot2_base_types_public_encryption_key::decode: ", (const Base_Type &)p_public_encryption_key); - return 0; -} +#include "ieee_1609dot2_base_types_public_encryption_key.hh" + +#include "loggers.hh" + +int ieee_1609dot2_base_types_public_encryption_key::encode(const Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, OCTETSTRING &p_data) { + loggers::get_instance().log(">>> ieee_1609dot2_base_types_public_encryption_key::encode: %s", p_public_encryption_key.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_public_encryption_key.encode(*p_public_encryption_key.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("ieee_1609dot2_base_types_public_encryption_key::encode: ", p_data); + + return 0; +} + +int ieee_1609dot2_base_types_public_encryption_key::decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, + params *p_params) { + loggers::get_instance().log_msg(">>> ieee_1609dot2_base_types_public_encryption_key::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_public_encryption_key.decode(*p_public_encryption_key.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< ieee_1609dot2_base_types_public_encryption_key::decode: ", (const Base_Type &)p_public_encryption_key); + return 0; +} diff --git a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.hh b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.hh index e0a5fb3a15d7d436be4052814e5c1fb74ea4c6f2..ee1bd5a64f6b4dc74ebc2855c4fed563c17f8606 100644 --- a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.hh +++ b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_encryption_key.hh @@ -1,15 +1,15 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "Ieee1609Dot2BaseTypes.hh" - -class ieee_1609dot2_base_types_public_encryption_key : public codec { -public: - explicit ieee_1609dot2_base_types_public_encryption_key() : codec(){}; - virtual ~ieee_1609dot2_base_types_public_encryption_key(){}; - - virtual int encode(const Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, params *p_params = NULL); -}; // End of class ieee_1609dot2_base_types_public_encryption_key +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "Ieee1609Dot2BaseTypes.hh" + +class ieee_1609dot2_base_types_public_encryption_key : public codec { +public: + explicit ieee_1609dot2_base_types_public_encryption_key() : codec(){}; + virtual ~ieee_1609dot2_base_types_public_encryption_key(){}; + + virtual int encode(const Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicEncryptionKey &p_public_encryption_key, params *p_params = NULL); +}; // End of class ieee_1609dot2_base_types_public_encryption_key diff --git a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.cc b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.cc index 482d9044cc15207d806673286c4c428584859115..421245d32ec0ed4eec0d30e0c1edbbbd9725ac94 100644 --- a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.cc +++ b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.cc @@ -1,30 +1,30 @@ -#include "ieee_1609dot2_base_types_public_verification_key.hh" - -#include "loggers.hh" - -int ieee_1609dot2_base_types_public_verification_key::encode(const Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, - OCTETSTRING & p_data) { - loggers::get_instance().log(">>> ieee_1609dot2_base_types_public_verification_key::encode: %s", p_public_verification_key.get_descriptor()->name); - - BITSTRING b; - TTCN_EncDec::clear_error(); - TTCN_Buffer buffer; - p_public_verification_key.encode(*p_public_verification_key.get_descriptor(), buffer, TTCN_EncDec::CT_OER); - p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); - loggers::get_instance().log_msg("ieee_1609dot2_base_types_public_verification_key::encode: ", p_data); - - return 0; -} - -int ieee_1609dot2_base_types_public_verification_key::decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, - params *p_params) { - loggers::get_instance().log_msg(">>> ieee_1609dot2_base_types_public_verification_key::decode: ", p_data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(p_data); - // _params = params; - p_public_verification_key.decode(*p_public_verification_key.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); - - loggers::get_instance().log_msg("<<< ieee_1609dot2_base_types_public_verification_key::decode: ", (const Base_Type &)p_public_verification_key); - return 0; -} +#include "ieee_1609dot2_base_types_public_verification_key.hh" + +#include "loggers.hh" + +int ieee_1609dot2_base_types_public_verification_key::encode(const Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, + OCTETSTRING & p_data) { + loggers::get_instance().log(">>> ieee_1609dot2_base_types_public_verification_key::encode: %s", p_public_verification_key.get_descriptor()->name); + + BITSTRING b; + TTCN_EncDec::clear_error(); + TTCN_Buffer buffer; + p_public_verification_key.encode(*p_public_verification_key.get_descriptor(), buffer, TTCN_EncDec::CT_OER); + p_data = OCTETSTRING(buffer.get_len(), buffer.get_data()); + loggers::get_instance().log_msg("ieee_1609dot2_base_types_public_verification_key::encode: ", p_data); + + return 0; +} + +int ieee_1609dot2_base_types_public_verification_key::decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, + params *p_params) { + loggers::get_instance().log_msg(">>> ieee_1609dot2_base_types_public_verification_key::decode: ", p_data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(p_data); + // _params = params; + p_public_verification_key.decode(*p_public_verification_key.get_descriptor(), decoding_buffer, TTCN_EncDec::CT_OER); + + loggers::get_instance().log_msg("<<< ieee_1609dot2_base_types_public_verification_key::decode: ", (const Base_Type &)p_public_verification_key); + return 0; +} diff --git a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.hh b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.hh index 5476edf4bb3514c6f706b0c0492680b7d36ca8de..809c9ca921427923d0373b34f83df2e67ec05f40 100644 --- a/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.hh +++ b/ccsrc/Protocols/Security/ieee_1609dot2_base_types_public_verification_key.hh @@ -1,17 +1,17 @@ -#pragma once - -#include "codec.hh" -#include "params.hh" - -#include "Ieee1609Dot2BaseTypes.hh" - -class ieee_1609dot2_base_types_public_verification_key - : public codec { -public: - explicit ieee_1609dot2_base_types_public_verification_key() - : codec(){}; - virtual ~ieee_1609dot2_base_types_public_verification_key(){}; - - virtual int encode(const Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, OCTETSTRING &p_data); - virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, params *p_params = NULL); -}; // End of class ieee_1609dot2_base_types_public_verification_key +#pragma once + +#include "codec.hh" +#include "params.hh" + +#include "Ieee1609Dot2BaseTypes.hh" + +class ieee_1609dot2_base_types_public_verification_key + : public codec { +public: + explicit ieee_1609dot2_base_types_public_verification_key() + : codec(){}; + virtual ~ieee_1609dot2_base_types_public_verification_key(){}; + + virtual int encode(const Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, OCTETSTRING &p_data); + virtual int decode(const OCTETSTRING &p_data, Ieee1609Dot2BaseTypes::PublicVerificationKey &p_public_verification_key, params *p_params = NULL); +}; // End of class ieee_1609dot2_base_types_public_verification_key diff --git a/ccsrc/Protocols/Security/module.mk b/ccsrc/Protocols/Security/module.mk index 7e7c4571badf2a54dcd31090407611d4b1ec6a72..722ac335d0c884857d69e89cc11480ff87d53237 100644 --- a/ccsrc/Protocols/Security/module.mk +++ b/ccsrc/Protocols/Security/module.mk @@ -1,40 +1,40 @@ -sources := certificates_loader.cc \ - etsi_ts103097_certificate_codec.cc \ - etsi_ts103097_data_codec.cc \ - etsi_ts103097_tobesigned_certificate_codec.cc \ - etsi_ts103097_tobesigned_data_codec.cc \ - hmac.cc \ - ieee_1609dot2_base_types_public_encryption_key.cc \ - ieee_1609dot2_base_types_public_verification_key.cc \ - security_cache.cc \ - security_db.cc \ - security_db_record.cc \ - security_ecc.cc \ - security_services.cc \ - sha256.cc \ - sha384.cc \ - -ifeq (AtsPki, $(ATS)) -sources += http_etsi_ieee1609dot2_codec.cc \ - etsi_ts102941_base_types_public_keys.cc \ - etsi_ts102941_data_codec.cc \ - etsi_ts102941_data_content_codec.cc \ - etsi_ts102941_types_authorization_inner_request.cc \ - etsi_ts102941_types_authorization_inner_response.cc \ - etsi_ts102941_types_authorization_shared_at_request.cc \ - etsi_ts102941_types_authorization_validation_request.cc \ - etsi_ts102941_types_authorization_validation_response.cc \ - etsi_ts102941_types_enrolment_inner_request.cc \ - etsi_ts102941_types_enrolment_inner_response.cc \ - -endif - -ifeq (AtsPki, $(ATS)) -sources += http_etsi_ieee1609dot2_codec.cc -endif - -ifeq (AtsRSUsSimulator, $(ATS)) -sources += http_etsi_ieee1609dot2_codec.cc -endif - -includes := . +sources := certificates_loader.cc \ + etsi_ts103097_certificate_codec.cc \ + etsi_ts103097_data_codec.cc \ + etsi_ts103097_tobesigned_certificate_codec.cc \ + etsi_ts103097_tobesigned_data_codec.cc \ + hmac.cc \ + ieee_1609dot2_base_types_public_encryption_key.cc \ + ieee_1609dot2_base_types_public_verification_key.cc \ + security_cache.cc \ + security_db.cc \ + security_db_record.cc \ + security_ecc.cc \ + security_services.cc \ + sha256.cc \ + sha384.cc \ + +ifeq (AtsPki, $(ATS)) +sources += http_etsi_ieee1609dot2_codec.cc \ + etsi_ts102941_base_types_public_keys.cc \ + etsi_ts102941_data_codec.cc \ + etsi_ts102941_data_content_codec.cc \ + etsi_ts102941_types_authorization_inner_request.cc \ + etsi_ts102941_types_authorization_inner_response.cc \ + etsi_ts102941_types_authorization_shared_at_request.cc \ + etsi_ts102941_types_authorization_validation_request.cc \ + etsi_ts102941_types_authorization_validation_response.cc \ + etsi_ts102941_types_enrolment_inner_request.cc \ + etsi_ts102941_types_enrolment_inner_response.cc \ + +endif + +ifeq (AtsPki, $(ATS)) +sources += http_etsi_ieee1609dot2_codec.cc +endif + +ifeq (AtsRSUsSimulator, $(ATS)) +sources += http_etsi_ieee1609dot2_codec.cc +endif + +includes := . diff --git a/ccsrc/Protocols/Security/security_cache.cc b/ccsrc/Protocols/Security/security_cache.cc index fc7bc5a589efeee30424fa0ce5cae7b4e36ec2b2..a898bb8c6187ce2c7d3a95f4da0c527973a633b0 100644 --- a/ccsrc/Protocols/Security/security_cache.cc +++ b/ccsrc/Protocols/Security/security_cache.cc @@ -1,411 +1,411 @@ -/*! - * \file security_cache.cc - * \brief Source file for a certificates caching storage mechanism. - * It is used to store certificates received from neighbors and not present in the data base - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include - -#include "security_cache.hh" - -#include "params.hh" - -#include "converter.hh" - -using namespace std; // Required for isnan() -#include "etsi_ts103097_certificate_codec.hh" - -#include "loggers.hh" - -bool security_cache_comp::operator()(const OCTETSTRING &p_lhs, const OCTETSTRING &p_rhs) const { - // loggers::get_instance().log_msg(">>> security_cache_comp::operator(): p_lhs= ", p_lhs); - // loggers::get_instance().log_msg(">>> security_cache_comp::operator(): p_rhs= ", p_rhs); - unsigned char *first1 = (unsigned char *)static_cast(p_lhs); - unsigned char *first2 = (unsigned char *)static_cast(p_rhs); - unsigned char *last1 = p_lhs.lengthof() + (unsigned char *)static_cast(p_lhs); - unsigned char *last2 = p_rhs.lengthof() + (unsigned char *)static_cast(p_rhs); - - while (first1 != last1) { - if ((first2 == last2) || (*first2 < *first1)) { - return false; - } else if (*first1 < *first2) { - return true; - } - ++first1; - ++first2; - } // End of 'while' statement - return (first2 != last2); -} - -security_cache::security_cache() : _certificates(), _hashed_id8s() { loggers::get_instance().log(">>> security_cache::security_cache"); } // End of ctor - -security_cache::~security_cache() { - loggers::get_instance().log(">>> security_cache::~security_cache"); - clear(); -} // End of dtor - -int security_cache::clear() { - loggers::get_instance().log(">>> security_cache::clear"); - _certificates.clear(); // Smart pointers will do the job - _hashed_id8s.clear(); - - return 0; -} // End of clear method - -int security_cache::get_certificate_id(const OCTETSTRING &p_hashed_id8, std::string &p_certificate_id) const { - loggers::get_instance().log_msg(">>> security_cache::get_certificate_id: ", p_hashed_id8); - - std::map::const_iterator it = _hashed_id8s.find(p_hashed_id8); - // std::vector v(static_cast(p_hashed_id8), p_hashed_id8.lengthof() + static_cast(p_hashed_id8)); - // std::map, std::string>::const_iterator it = _hashed_id8s.find(v); - if (it == _hashed_id8s.cend()) { - dump(); - p_certificate_id = ""; - return -1; - } - p_certificate_id = it->second; - - return 0; -} - -int security_cache::get_certificate(const std::string &p_certificate_id, OCTETSTRING &p_certificate) const { - loggers::get_instance().log(">>> security_cache::get_certificate: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_certificate: record not found"); - dump(); - return -1; - } - p_certificate = it->second.get()->certificate(); - - return 0; -} - -int security_cache::get_certificate(const std::string &p_certificate_id, Ieee1609Dot2::CertificateBase &p_certificate) const { - loggers::get_instance().log(">>> security_cache::get_certificate: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_certificate: record not found"); - return -1; - } - p_certificate = it->second.get()->decoded_certificate(); - - return 0; -} - -int security_cache::get_certificate(const OCTETSTRING &p_hashed_id3, Ieee1609Dot2::CertificateBase &p_certificate) const { - loggers::get_instance().log_msg(">>> security_cache::get_certificate: ", p_hashed_id3); - - std::map::const_iterator s; - for (s = _hashed_id8s.cbegin(); s != _hashed_id8s.cend(); ++s) { - if ((p_hashed_id3[2] == (s->first)[(s->first).lengthof() - 1]) && (p_hashed_id3[1] == (s->first)[(s->first).lengthof() - 2]) && - (p_hashed_id3[0] == (s->first)[(s->first).lengthof() - 3])) { - break; - } - } // End of 'for' statement - if (s == _hashed_id8s.cend()) { - loggers::get_instance().warning("security_cache::get_certificate: hashedId3 does not match"); - return -1; - } - /*TODO std::map::const_iterator s = std::find_if( - _hashed_id8s.cbegin(), - _hashed_id8s.cend(), - hashed_id_matching - );*/ - std::map>::const_iterator it = _certificates.find(s->second); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_certificate: record not found"); - return -1; - } - p_certificate = it->second.get()->decoded_certificate(); - - return 0; -} - -int security_cache::get_certificate_hashed_id3(const OCTETSTRING &p_hashed_id3, std::string &p_certificate_id) const { - loggers::get_instance().log_msg(">>> security_cache::get_certificate_hashed_id3: ", p_hashed_id3); - - std::map::const_iterator s; - for (s = _hashed_id8s.cbegin(); s != _hashed_id8s.cend(); ++s) { - if ((p_hashed_id3[2] == (s->first)[(s->first).lengthof() - 1]) && (p_hashed_id3[1] == (s->first)[(s->first).lengthof() - 2]) && - (p_hashed_id3[0] == (s->first)[(s->first).lengthof() - 3])) { - break; - } - } // End of 'for' statement - if (s == _hashed_id8s.cend()) { - loggers::get_instance().warning("security_cache::get_certificate_hashed_id3: hashedId3 does not match"); - return -1; - } - /*TODO std::map::const_iterator s = std::find_if( - _hashed_id8s.cbegin(), - _hashed_id8s.cend(), - hashed_id_matching - );*/ - p_certificate_id = s->second; - - return 0; -} - -int security_cache::get_issuer(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id_issuer) const { - loggers::get_instance().log(">>> security_cache::get_issuer: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_issuer: record not found"); - return -1; - } - p_hashed_id_issuer = it->second.get()->issuer(); - - return 0; -} - -int security_cache::get_hashed_id(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id) const { - loggers::get_instance().log(">>> security_cache::get_hashed_id: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_hashed_id: record not found"); - return -1; - } - p_hashed_id = it->second.get()->hashed_id(); - - return 0; -} - -int security_cache::get_hash(const std::string &p_certificate_id, OCTETSTRING &p_hash) const { - loggers::get_instance().log(">>> security_cache::get_hash: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_hash: record not found"); - return -1; - } - p_hash = it->second.get()->hash(); - - return 0; -} - -int security_cache::get_hash_sha_256(const std::string &p_certificate_id, OCTETSTRING &p_hash) const { - loggers::get_instance().log(">>> security_cache::get_hash_sha_256: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_hash_sha_256: record not found"); - return -1; - } - p_hash = it->second.get()->hash_sha_256(); - - return 0; -} - -int security_cache::get_private_key(const std::string &p_certificate_id, OCTETSTRING &p_private_key) const { - loggers::get_instance().log(">>> security_cache::get_private_key: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_private_key: record not found"); - return -1; - } - p_private_key = it->second.get()->private_key(); - - return 0; -} - -int security_cache::get_public_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) const { - loggers::get_instance().log(">>> security_cache::get_public_keys: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_public_keys: record not found"); - return -1; - } - p_public_key_x = it->second.get()->public_key_x(); - p_public_key_y = it->second.get()->public_key_y(); - - return 0; -} - -int security_cache::get_public_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_comp_key, INTEGER &p_comp_mode) const { - loggers::get_instance().log(">>> security_cache::get_public_comp_key: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_public_comp_key: record not found"); - return -1; - } - const OCTETSTRING public_comp_key = it->second.get()->public_comp_key(); // 33 or 49 bytes length - p_public_comp_key = OCTETSTRING(public_comp_key.lengthof() - 1, 1 + static_cast(public_comp_key)); // 32 or 48 bytes length - p_comp_mode = INTEGER(((public_comp_key[0].get_octet() % 2) == 0) ? 0 : 1); // compressed-y-0 or compressed-y-1 - - return 0; -} - -int security_cache::get_private_enc_key(const std::string &p_certificate_id, OCTETSTRING &p_private_enc_key) const { - loggers::get_instance().log(">>> security_cache::get_private_enc_key: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_private_enc_key: record not found"); - return -1; - } - p_private_enc_key = it->second.get()->private_enc_key(); - - return 0; -} - -int security_cache::get_public_enc_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y) const { - loggers::get_instance().log(">>> security_cache::get_public_enc_keys: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_public_enc_keys: record not found"); - return -1; - } - p_public_enc_key_x = it->second.get()->public_enc_key_x(); - p_public_enc_key_y = it->second.get()->public_enc_key_y(); - - return 0; -} - -int security_cache::get_public_enc_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_comp_key, INTEGER &p_enc_comp_mode) const { - loggers::get_instance().log(">>> security_cache::get_public_enc_comp_key: '%s'", p_certificate_id.c_str()); - - std::map>::const_iterator it = _certificates.find(p_certificate_id); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_cache::get_public_enc_comp_key: record not found"); - return -1; - } - const OCTETSTRING public_enc_comp_key = it->second.get()->public_enc_comp_key(); // 33 or 49 bytes length - p_public_enc_comp_key = OCTETSTRING(public_enc_comp_key.lengthof() - 1, 1 + static_cast(public_enc_comp_key)); // 32 or 48 bytes length - p_enc_comp_mode = INTEGER(((public_enc_comp_key[0].get_octet() % 2) == 0) ? 0 : 1); // compressed-y-0 or compressed-y-1 - - return 0; -} - -bool security_cache::fill_vector(OCTETSTRING &p_vector, const OCTETSTRING &p_org) { - if (p_org.is_bound()) { - p_vector = p_org; - return true; - } - p_vector = OCTETSTRING(0, nullptr); - return false; -} - -int security_cache::store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, - const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, - const INTEGER &p_public_compressed_key_mode, const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, - const OCTETSTRING &p_hashed_id8, const OCTETSTRING &p_issuer, const OCTETSTRING &p_private_enc_key, - const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, - const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_compressed_key_mode) { - loggers::get_instance().log_msg(">>> security_cache::store_certificate: ", p_cert_id); - - std::string key(static_cast(p_cert_id)); - OCTETSTRING cert, private_key, public_key_x, public_key_y, public_comp_key, hash, hash_sha_256, hashed_id8, issuer; - OCTETSTRING private_enc_key, public_enc_key_x, public_enc_key_y, public_enc_comp_key; - - security_cache::fill_vector(cert, p_cert); - security_cache::fill_vector(private_key, p_private_key); - - security_cache::fill_vector(public_key_x, p_public_key_x); - security_cache::fill_vector(public_key_y, p_public_key_y); - if (fill_vector(public_comp_key, p_public_compressed_key)) { - public_comp_key = - int2oct((unsigned char)(2 + p_public_compressed_key_mode), 1) + public_comp_key; // Add one byte to indicate cmpressed-y-0 (0x02) or compressed-y-1 (0x03) - loggers::get_instance().log_msg("security_cache::store_certificate: public_comp_key: ", public_comp_key); - } - - security_cache::fill_vector(hash, p_hash); - security_cache::fill_vector(hash_sha_256, p_hash_sha_256); - security_cache::fill_vector(hashed_id8, p_hashed_id8); - security_cache::fill_vector(issuer, p_issuer); - - security_cache::fill_vector(private_enc_key, p_private_enc_key); - security_cache::fill_vector(public_enc_key_x, p_public_enc_key_x); - security_cache::fill_vector(public_enc_key_y, p_public_enc_key_y); - if (fill_vector(public_enc_comp_key, p_public_enc_compressed_key)) { - public_enc_comp_key = int2oct((unsigned char)(2 + p_public_compressed_key_mode), 1) + - public_enc_comp_key; // Add one byte to indicate cmpressed-y-0 (0x02) or compressed-y-1 (0x03) - loggers::get_instance().log_msg("security_cache::store_certificate: public_enc_comp_key: ", public_enc_comp_key); - } - - Ieee1609Dot2::CertificateBase decoded_certificate; - etsi_ts103097_certificate_codec codec; - codec.decode(p_cert, decoded_certificate); - loggers::get_instance().log_msg("security_cache::store_certificate: Decoded certificate: ", decoded_certificate); - security_db_record *p = new security_db_record(key, // Certificate id - cert, // Certificate - decoded_certificate, - issuer, // Hashed ID for the issuer - hash, // Whole-certificate hash - hash_sha_256, // Whole-certificate hash using SHA-256 - hashed_id8, // Whole-certificate hashed ID - private_key, // Private key - public_key_x, // Public key X-coordinate - public_key_y, // Public key Y-coordinate - public_comp_key, // Public compressed key, 33 or 49 bytes - private_enc_key, // Private encryption key - public_enc_key_x, // Public encryption key X-coordinate - public_enc_key_y, // Public encryption key Y-coordinate - public_enc_comp_key // Public encryption compressed key, 33 or 49 bytes - ); - if (p == nullptr) { - return -1; - } - std::map>::const_iterator i = _certificates.find(key); - if (i != _certificates.cend()) { - _certificates.erase(i); - } - - _certificates.insert(std::pair>(key, std::unique_ptr(p))); - - std::map::const_iterator h = _hashed_id8s.find(hashed_id8); - // std::vector v(static_cast(hashed_id8), hashed_id8.lengthof() + static_cast(hashed_id8)); - // std::map, std::string>::const_iterator h = _hashed_id8s.find(v); - if (h != _hashed_id8s.cend()) { - loggers::get_instance().log_msg("security_cache::store_certificate: Replace entry ", h->first); - _hashed_id8s.erase(h); - } - loggers::get_instance().log_msg("security_cache::store_certificate: Add entry ", hashed_id8); - loggers::get_instance().log("security_cache::store_certificate: Add entry for key %s", key.c_str()); - _hashed_id8s.insert(std::pair(hashed_id8, key)); - //_hashed_id8s.insert(std::pair, std::string&>(v, key)); - - // dump(); - - return 0; -} - -void security_cache::dump() const { - loggers::get_instance().log("security_cache::dump_certificates: # items = %d", _certificates.size()); - for (std::map>::const_iterator it = _certificates.cbegin(); it != _certificates.cend(); ++it) { - security_db_record *p = it->second.get(); - loggers::get_instance().log("security_cache::dump: certificate_id = %s", p->certificate_id().c_str()); - loggers::get_instance().log_msg("security_cache::dump: certificate = ", p->certificate()); - loggers::get_instance().log_msg("security_cache::dump: decoded certificate = ", p->decoded_certificate()); - loggers::get_instance().log_msg("security_cache::dump: issuer = ", p->issuer()); - loggers::get_instance().log_msg("security_cache::dump: hashed_id = ", p->hashed_id()); - loggers::get_instance().log_msg("security_cache::dump: hash = ", p->hash()); - loggers::get_instance().log_msg("security_cache::dump: hash_sha_256 = ", p->hash_sha_256()); - loggers::get_instance().log_msg("security_cache::dump: private_key = ", p->private_key()); - loggers::get_instance().log_msg("security_cache::dump: public_key_x = ", p->public_key_x()); - loggers::get_instance().log_msg("security_cache::dump: public_key_y = ", p->public_key_y()); - loggers::get_instance().log_msg("security_cache::dump: public_comp_key = ", p->public_comp_key()); - loggers::get_instance().log_msg("security_cache::dump: private_enc_key = ", p->private_enc_key()); - loggers::get_instance().log_msg("security_cache::dump: public_enc_key_x = ", p->public_enc_key_x()); - loggers::get_instance().log_msg("security_cache::dump: public_enc_key_y = ", p->public_enc_key_y()); - loggers::get_instance().log_msg("security_cache::dump: public_enc_comp_key = ", p->public_enc_comp_key()); - } // End of 'for' statement - // for (std::map::const_iterator it = _hashed_id8s.cbegin(); it != _hashed_id8s.cend(); ++it) { - loggers::get_instance().log("security_cache::dump: Hashedid8 table length: %d", _hashed_id8s.size()); - for (std::map*/, std::string>::const_iterator it = _hashed_id8s.cbegin(); it != _hashed_id8s.cend(); ++it) { - loggers::get_instance().log_msg("security_cache::dump: Hashedid8 key = ", it->first); - loggers::get_instance().log("security_cache::dump: Hashedid8 idx ==> %s", it->second.c_str()); - } // End of 'for' statement -} // End of method dump +/*! + * \file security_cache.cc + * \brief Source file for a certificates caching storage mechanism. + * It is used to store certificates received from neighbors and not present in the data base + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include + +#include "security_cache.hh" + +#include "params.hh" + +#include "converter.hh" + +using namespace std; // Required for isnan() +#include "etsi_ts103097_certificate_codec.hh" + +#include "loggers.hh" + +bool security_cache_comp::operator()(const OCTETSTRING &p_lhs, const OCTETSTRING &p_rhs) const { + // loggers::get_instance().log_msg(">>> security_cache_comp::operator(): p_lhs= ", p_lhs); + // loggers::get_instance().log_msg(">>> security_cache_comp::operator(): p_rhs= ", p_rhs); + unsigned char *first1 = (unsigned char *)static_cast(p_lhs); + unsigned char *first2 = (unsigned char *)static_cast(p_rhs); + unsigned char *last1 = p_lhs.lengthof() + (unsigned char *)static_cast(p_lhs); + unsigned char *last2 = p_rhs.lengthof() + (unsigned char *)static_cast(p_rhs); + + while (first1 != last1) { + if ((first2 == last2) || (*first2 < *first1)) { + return false; + } else if (*first1 < *first2) { + return true; + } + ++first1; + ++first2; + } // End of 'while' statement + return (first2 != last2); +} + +security_cache::security_cache() : _certificates(), _hashed_id8s() { loggers::get_instance().log(">>> security_cache::security_cache"); } // End of ctor + +security_cache::~security_cache() { + loggers::get_instance().log(">>> security_cache::~security_cache"); + clear(); +} // End of dtor + +int security_cache::clear() { + loggers::get_instance().log(">>> security_cache::clear"); + _certificates.clear(); // Smart pointers will do the job + _hashed_id8s.clear(); + + return 0; +} // End of clear method + +int security_cache::get_certificate_id(const OCTETSTRING &p_hashed_id8, std::string &p_certificate_id) const { + loggers::get_instance().log_msg(">>> security_cache::get_certificate_id: ", p_hashed_id8); + + std::map::const_iterator it = _hashed_id8s.find(p_hashed_id8); + // std::vector v(static_cast(p_hashed_id8), p_hashed_id8.lengthof() + static_cast(p_hashed_id8)); + // std::map, std::string>::const_iterator it = _hashed_id8s.find(v); + if (it == _hashed_id8s.cend()) { + dump(); + p_certificate_id = ""; + return -1; + } + p_certificate_id = it->second; + + return 0; +} + +int security_cache::get_certificate(const std::string &p_certificate_id, OCTETSTRING &p_certificate) const { + loggers::get_instance().log(">>> security_cache::get_certificate: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_certificate: record not found"); + dump(); + return -1; + } + p_certificate = it->second.get()->certificate(); + + return 0; +} + +int security_cache::get_certificate(const std::string &p_certificate_id, Ieee1609Dot2::CertificateBase &p_certificate) const { + loggers::get_instance().log(">>> security_cache::get_certificate: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_certificate: record not found"); + return -1; + } + p_certificate = it->second.get()->decoded_certificate(); + + return 0; +} + +int security_cache::get_certificate(const OCTETSTRING &p_hashed_id3, Ieee1609Dot2::CertificateBase &p_certificate) const { + loggers::get_instance().log_msg(">>> security_cache::get_certificate: ", p_hashed_id3); + + std::map::const_iterator s; + for (s = _hashed_id8s.cbegin(); s != _hashed_id8s.cend(); ++s) { + if ((p_hashed_id3[2] == (s->first)[(s->first).lengthof() - 1]) && (p_hashed_id3[1] == (s->first)[(s->first).lengthof() - 2]) && + (p_hashed_id3[0] == (s->first)[(s->first).lengthof() - 3])) { + break; + } + } // End of 'for' statement + if (s == _hashed_id8s.cend()) { + loggers::get_instance().warning("security_cache::get_certificate: hashedId3 does not match"); + return -1; + } + /*TODO std::map::const_iterator s = std::find_if( + _hashed_id8s.cbegin(), + _hashed_id8s.cend(), + hashed_id_matching + );*/ + std::map>::const_iterator it = _certificates.find(s->second); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_certificate: record not found"); + return -1; + } + p_certificate = it->second.get()->decoded_certificate(); + + return 0; +} + +int security_cache::get_certificate_hashed_id3(const OCTETSTRING &p_hashed_id3, std::string &p_certificate_id) const { + loggers::get_instance().log_msg(">>> security_cache::get_certificate_hashed_id3: ", p_hashed_id3); + + std::map::const_iterator s; + for (s = _hashed_id8s.cbegin(); s != _hashed_id8s.cend(); ++s) { + if ((p_hashed_id3[2] == (s->first)[(s->first).lengthof() - 1]) && (p_hashed_id3[1] == (s->first)[(s->first).lengthof() - 2]) && + (p_hashed_id3[0] == (s->first)[(s->first).lengthof() - 3])) { + break; + } + } // End of 'for' statement + if (s == _hashed_id8s.cend()) { + loggers::get_instance().warning("security_cache::get_certificate_hashed_id3: hashedId3 does not match"); + return -1; + } + /*TODO std::map::const_iterator s = std::find_if( + _hashed_id8s.cbegin(), + _hashed_id8s.cend(), + hashed_id_matching + );*/ + p_certificate_id = s->second; + + return 0; +} + +int security_cache::get_issuer(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id_issuer) const { + loggers::get_instance().log(">>> security_cache::get_issuer: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_issuer: record not found"); + return -1; + } + p_hashed_id_issuer = it->second.get()->issuer(); + + return 0; +} + +int security_cache::get_hashed_id(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id) const { + loggers::get_instance().log(">>> security_cache::get_hashed_id: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_hashed_id: record not found"); + return -1; + } + p_hashed_id = it->second.get()->hashed_id(); + + return 0; +} + +int security_cache::get_hash(const std::string &p_certificate_id, OCTETSTRING &p_hash) const { + loggers::get_instance().log(">>> security_cache::get_hash: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_hash: record not found"); + return -1; + } + p_hash = it->second.get()->hash(); + + return 0; +} + +int security_cache::get_hash_sha_256(const std::string &p_certificate_id, OCTETSTRING &p_hash) const { + loggers::get_instance().log(">>> security_cache::get_hash_sha_256: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_hash_sha_256: record not found"); + return -1; + } + p_hash = it->second.get()->hash_sha_256(); + + return 0; +} + +int security_cache::get_private_key(const std::string &p_certificate_id, OCTETSTRING &p_private_key) const { + loggers::get_instance().log(">>> security_cache::get_private_key: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_private_key: record not found"); + return -1; + } + p_private_key = it->second.get()->private_key(); + + return 0; +} + +int security_cache::get_public_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) const { + loggers::get_instance().log(">>> security_cache::get_public_keys: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_public_keys: record not found"); + return -1; + } + p_public_key_x = it->second.get()->public_key_x(); + p_public_key_y = it->second.get()->public_key_y(); + + return 0; +} + +int security_cache::get_public_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_comp_key, INTEGER &p_comp_mode) const { + loggers::get_instance().log(">>> security_cache::get_public_comp_key: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_public_comp_key: record not found"); + return -1; + } + const OCTETSTRING public_comp_key = it->second.get()->public_comp_key(); // 33 or 49 bytes length + p_public_comp_key = OCTETSTRING(public_comp_key.lengthof() - 1, 1 + static_cast(public_comp_key)); // 32 or 48 bytes length + p_comp_mode = INTEGER(((public_comp_key[0].get_octet() % 2) == 0) ? 0 : 1); // compressed-y-0 or compressed-y-1 + + return 0; +} + +int security_cache::get_private_enc_key(const std::string &p_certificate_id, OCTETSTRING &p_private_enc_key) const { + loggers::get_instance().log(">>> security_cache::get_private_enc_key: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_private_enc_key: record not found"); + return -1; + } + p_private_enc_key = it->second.get()->private_enc_key(); + + return 0; +} + +int security_cache::get_public_enc_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y) const { + loggers::get_instance().log(">>> security_cache::get_public_enc_keys: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_public_enc_keys: record not found"); + return -1; + } + p_public_enc_key_x = it->second.get()->public_enc_key_x(); + p_public_enc_key_y = it->second.get()->public_enc_key_y(); + + return 0; +} + +int security_cache::get_public_enc_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_comp_key, INTEGER &p_enc_comp_mode) const { + loggers::get_instance().log(">>> security_cache::get_public_enc_comp_key: '%s'", p_certificate_id.c_str()); + + std::map>::const_iterator it = _certificates.find(p_certificate_id); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_cache::get_public_enc_comp_key: record not found"); + return -1; + } + const OCTETSTRING public_enc_comp_key = it->second.get()->public_enc_comp_key(); // 33 or 49 bytes length + p_public_enc_comp_key = OCTETSTRING(public_enc_comp_key.lengthof() - 1, 1 + static_cast(public_enc_comp_key)); // 32 or 48 bytes length + p_enc_comp_mode = INTEGER(((public_enc_comp_key[0].get_octet() % 2) == 0) ? 0 : 1); // compressed-y-0 or compressed-y-1 + + return 0; +} + +bool security_cache::fill_vector(OCTETSTRING &p_vector, const OCTETSTRING &p_org) { + if (p_org.is_bound()) { + p_vector = p_org; + return true; + } + p_vector = OCTETSTRING(0, nullptr); + return false; +} + +int security_cache::store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, + const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, + const INTEGER &p_public_compressed_key_mode, const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, + const OCTETSTRING &p_hashed_id8, const OCTETSTRING &p_issuer, const OCTETSTRING &p_private_enc_key, + const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, + const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_compressed_key_mode) { + loggers::get_instance().log_msg(">>> security_cache::store_certificate: ", p_cert_id); + + std::string key(static_cast(p_cert_id)); + OCTETSTRING cert, private_key, public_key_x, public_key_y, public_comp_key, hash, hash_sha_256, hashed_id8, issuer; + OCTETSTRING private_enc_key, public_enc_key_x, public_enc_key_y, public_enc_comp_key; + + security_cache::fill_vector(cert, p_cert); + security_cache::fill_vector(private_key, p_private_key); + + security_cache::fill_vector(public_key_x, p_public_key_x); + security_cache::fill_vector(public_key_y, p_public_key_y); + if (fill_vector(public_comp_key, p_public_compressed_key)) { + public_comp_key = + int2oct((unsigned char)(2 + p_public_compressed_key_mode), 1) + public_comp_key; // Add one byte to indicate cmpressed-y-0 (0x02) or compressed-y-1 (0x03) + loggers::get_instance().log_msg("security_cache::store_certificate: public_comp_key: ", public_comp_key); + } + + security_cache::fill_vector(hash, p_hash); + security_cache::fill_vector(hash_sha_256, p_hash_sha_256); + security_cache::fill_vector(hashed_id8, p_hashed_id8); + security_cache::fill_vector(issuer, p_issuer); + + security_cache::fill_vector(private_enc_key, p_private_enc_key); + security_cache::fill_vector(public_enc_key_x, p_public_enc_key_x); + security_cache::fill_vector(public_enc_key_y, p_public_enc_key_y); + if (fill_vector(public_enc_comp_key, p_public_enc_compressed_key)) { + public_enc_comp_key = int2oct((unsigned char)(2 + p_public_compressed_key_mode), 1) + + public_enc_comp_key; // Add one byte to indicate cmpressed-y-0 (0x02) or compressed-y-1 (0x03) + loggers::get_instance().log_msg("security_cache::store_certificate: public_enc_comp_key: ", public_enc_comp_key); + } + + Ieee1609Dot2::CertificateBase decoded_certificate; + etsi_ts103097_certificate_codec codec; + codec.decode(p_cert, decoded_certificate); + loggers::get_instance().log_msg("security_cache::store_certificate: Decoded certificate: ", decoded_certificate); + security_db_record *p = new security_db_record(key, // Certificate id + cert, // Certificate + decoded_certificate, + issuer, // Hashed ID for the issuer + hash, // Whole-certificate hash + hash_sha_256, // Whole-certificate hash using SHA-256 + hashed_id8, // Whole-certificate hashed ID + private_key, // Private key + public_key_x, // Public key X-coordinate + public_key_y, // Public key Y-coordinate + public_comp_key, // Public compressed key, 33 or 49 bytes + private_enc_key, // Private encryption key + public_enc_key_x, // Public encryption key X-coordinate + public_enc_key_y, // Public encryption key Y-coordinate + public_enc_comp_key // Public encryption compressed key, 33 or 49 bytes + ); + if (p == nullptr) { + return -1; + } + std::map>::const_iterator i = _certificates.find(key); + if (i != _certificates.cend()) { + _certificates.erase(i); + } + + _certificates.insert(std::pair>(key, std::unique_ptr(p))); + + std::map::const_iterator h = _hashed_id8s.find(hashed_id8); + // std::vector v(static_cast(hashed_id8), hashed_id8.lengthof() + static_cast(hashed_id8)); + // std::map, std::string>::const_iterator h = _hashed_id8s.find(v); + if (h != _hashed_id8s.cend()) { + loggers::get_instance().log_msg("security_cache::store_certificate: Replace entry ", h->first); + _hashed_id8s.erase(h); + } + loggers::get_instance().log_msg("security_cache::store_certificate: Add entry ", hashed_id8); + loggers::get_instance().log("security_cache::store_certificate: Add entry for key %s", key.c_str()); + _hashed_id8s.insert(std::pair(hashed_id8, key)); + //_hashed_id8s.insert(std::pair, std::string&>(v, key)); + + // dump(); + + return 0; +} + +void security_cache::dump() const { + loggers::get_instance().log("security_cache::dump_certificates: # items = %d", _certificates.size()); + for (std::map>::const_iterator it = _certificates.cbegin(); it != _certificates.cend(); ++it) { + security_db_record *p = it->second.get(); + loggers::get_instance().log("security_cache::dump: certificate_id = %s", p->certificate_id().c_str()); + loggers::get_instance().log_msg("security_cache::dump: certificate = ", p->certificate()); + loggers::get_instance().log_msg("security_cache::dump: decoded certificate = ", p->decoded_certificate()); + loggers::get_instance().log_msg("security_cache::dump: issuer = ", p->issuer()); + loggers::get_instance().log_msg("security_cache::dump: hashed_id = ", p->hashed_id()); + loggers::get_instance().log_msg("security_cache::dump: hash = ", p->hash()); + loggers::get_instance().log_msg("security_cache::dump: hash_sha_256 = ", p->hash_sha_256()); + loggers::get_instance().log_msg("security_cache::dump: private_key = ", p->private_key()); + loggers::get_instance().log_msg("security_cache::dump: public_key_x = ", p->public_key_x()); + loggers::get_instance().log_msg("security_cache::dump: public_key_y = ", p->public_key_y()); + loggers::get_instance().log_msg("security_cache::dump: public_comp_key = ", p->public_comp_key()); + loggers::get_instance().log_msg("security_cache::dump: private_enc_key = ", p->private_enc_key()); + loggers::get_instance().log_msg("security_cache::dump: public_enc_key_x = ", p->public_enc_key_x()); + loggers::get_instance().log_msg("security_cache::dump: public_enc_key_y = ", p->public_enc_key_y()); + loggers::get_instance().log_msg("security_cache::dump: public_enc_comp_key = ", p->public_enc_comp_key()); + } // End of 'for' statement + // for (std::map::const_iterator it = _hashed_id8s.cbegin(); it != _hashed_id8s.cend(); ++it) { + loggers::get_instance().log("security_cache::dump: Hashedid8 table length: %d", _hashed_id8s.size()); + for (std::map*/, std::string>::const_iterator it = _hashed_id8s.cbegin(); it != _hashed_id8s.cend(); ++it) { + loggers::get_instance().log_msg("security_cache::dump: Hashedid8 key = ", it->first); + loggers::get_instance().log("security_cache::dump: Hashedid8 idx ==> %s", it->second.c_str()); + } // End of 'for' statement +} // End of method dump diff --git a/ccsrc/Protocols/Security/security_cache.hh b/ccsrc/Protocols/Security/security_cache.hh index 865df8f0e89910e2932a54168283a474f0fe1391..9cf2ab63ca1073a9e18d2d22358d4c437d9b612d 100644 --- a/ccsrc/Protocols/Security/security_cache.hh +++ b/ccsrc/Protocols/Security/security_cache.hh @@ -1,78 +1,78 @@ -/*! - * \file security_cache.hh - * \brief Header file for a certificates caching storage mechanism. - * It is used to store certificates received from neighbors and not present in the data base - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -#include "security_db_record.hh" - -class OCTETSTRING; //! TITAN forward declaration -class INTEGER; //! TITAN forward declaration -class CHARSTRING; //! TITAN forward declaration - -struct security_cache_comp { - bool operator()(const OCTETSTRING &p_lhs, const OCTETSTRING &p_rhs) const; -}; - -/*! - * \class security_cache - * \brief This class provides security record description for in memory security database. In memory mens there is no disk load/save mechanism - */ -class security_cache { - static bool fill_vector(OCTETSTRING &p_vector, const OCTETSTRING &p_org); - -protected: /*! \protectedsection */ - // TODO Enforce with const security_cache_record, and const std::string - std::map> _certificates; //! List of the certificates indexed by the certificate identifier - std::map _hashed_id8s; //! List of the certificates indexed by the HashedId8 - // std::map, std::string> _hashed_id8s; //! List of the certificates indexed by the HashedId8 - -public: /*! \publicsection */ - /*! - * \brief Default ctor - */ - security_cache(); - /*! - * \brief Default private dtor - */ - virtual ~security_cache(); - - int get_certificate_id(const OCTETSTRING &p_hashed_id8, std::string &p_certificate_id) const; - int get_certificate(const std::string &p_certificate_id, OCTETSTRING &p_certificate) const; - int get_certificate(const std::string &p_certificate_id, Ieee1609Dot2::CertificateBase &p_certificate) const; - int get_certificate(const OCTETSTRING &p_hashed_id3, Ieee1609Dot2::CertificateBase &p_certificate) const; - int get_certificate_hashed_id3(const OCTETSTRING &p_hashed_id3, std::string &p_certificate_id) const; - int get_issuer(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id_issuer) const; - int get_hashed_id(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id) const; - int get_hash(const std::string &p_certificate_id, OCTETSTRING &p_hash) const; - int get_hash_sha_256(const std::string &p_certificate_id, OCTETSTRING &p_hash) const; - int get_private_key(const std::string &p_certificate_id, OCTETSTRING &p_private_key) const; - int get_public_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) const; - int get_public_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_comp_key, INTEGER &p_comp_mode) const; - int get_private_enc_key(const std::string &p_certificate_id, OCTETSTRING &p_private_enc_key) const; - int get_public_enc_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y) const; - int get_public_enc_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_comp_key, INTEGER &p_enc_comp_mode) const; - - virtual int store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, - const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, const INTEGER &p_public_compressed_key_mode, - const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, - const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, - const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_compressed_key_mode); - - virtual int clear(); - - void dump() const; - -}; // End of class security_cache +/*! + * \file security_cache.hh + * \brief Header file for a certificates caching storage mechanism. + * It is used to store certificates received from neighbors and not present in the data base + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +#include "security_db_record.hh" + +class OCTETSTRING; //! TITAN forward declaration +class INTEGER; //! TITAN forward declaration +class CHARSTRING; //! TITAN forward declaration + +struct security_cache_comp { + bool operator()(const OCTETSTRING &p_lhs, const OCTETSTRING &p_rhs) const; +}; + +/*! + * \class security_cache + * \brief This class provides security record description for in memory security database. In memory mens there is no disk load/save mechanism + */ +class security_cache { + static bool fill_vector(OCTETSTRING &p_vector, const OCTETSTRING &p_org); + +protected: /*! \protectedsection */ + // TODO Enforce with const security_cache_record, and const std::string + std::map> _certificates; //! List of the certificates indexed by the certificate identifier + std::map _hashed_id8s; //! List of the certificates indexed by the HashedId8 + // std::map, std::string> _hashed_id8s; //! List of the certificates indexed by the HashedId8 + +public: /*! \publicsection */ + /*! + * \brief Default ctor + */ + security_cache(); + /*! + * \brief Default private dtor + */ + virtual ~security_cache(); + + int get_certificate_id(const OCTETSTRING &p_hashed_id8, std::string &p_certificate_id) const; + int get_certificate(const std::string &p_certificate_id, OCTETSTRING &p_certificate) const; + int get_certificate(const std::string &p_certificate_id, Ieee1609Dot2::CertificateBase &p_certificate) const; + int get_certificate(const OCTETSTRING &p_hashed_id3, Ieee1609Dot2::CertificateBase &p_certificate) const; + int get_certificate_hashed_id3(const OCTETSTRING &p_hashed_id3, std::string &p_certificate_id) const; + int get_issuer(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id_issuer) const; + int get_hashed_id(const std::string &p_certificate_id, OCTETSTRING &p_hashed_id) const; + int get_hash(const std::string &p_certificate_id, OCTETSTRING &p_hash) const; + int get_hash_sha_256(const std::string &p_certificate_id, OCTETSTRING &p_hash) const; + int get_private_key(const std::string &p_certificate_id, OCTETSTRING &p_private_key) const; + int get_public_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y) const; + int get_public_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_comp_key, INTEGER &p_comp_mode) const; + int get_private_enc_key(const std::string &p_certificate_id, OCTETSTRING &p_private_enc_key) const; + int get_public_enc_keys(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y) const; + int get_public_enc_comp_key(const std::string &p_certificate_id, OCTETSTRING &p_public_enc_comp_key, INTEGER &p_enc_comp_mode) const; + + virtual int store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, + const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, const INTEGER &p_public_compressed_key_mode, + const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, + const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, + const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_compressed_key_mode); + + virtual int clear(); + + void dump() const; + +}; // End of class security_cache diff --git a/ccsrc/Protocols/Security/security_db.cc b/ccsrc/Protocols/Security/security_db.cc index 6ad435f730cd1365c0a90ff35e45a52b7e98c744..36af16c2861d07bbbaebd33daec5559667160109 100644 --- a/ccsrc/Protocols/Security/security_db.cc +++ b/ccsrc/Protocols/Security/security_db.cc @@ -1,64 +1,64 @@ -#include - -#include "security_db.hh" - -#include "params.hh" - -#include "converter.hh" - -using namespace std; // Required for isnan() -#include "certificates_loader.hh" - -#include "etsi_ts103097_certificate_codec.hh" - -#include "loggers.hh" - -security_db::security_db(const std::string &p_db_path) { - loggers::get_instance().log(">>> security_db::security_db: '%s'", p_db_path.c_str()); - - load_from_files(p_db_path); - dump(); -} // End of ctor - -security_db::~security_db() { loggers::get_instance().log(">>> security_db::~security_db"); } // End of dtor - -int security_db::load_from_files(const std::string &p_db_path) { - loggers::get_instance().log(">>> security_db::load_from_files: '%s'", p_db_path.c_str()); - - if (certificates_loader::get_instance().build_path(p_db_path) == -1) { - loggers::get_instance().log(">>> security_db::load_from_files: certificates_loader::build_path method failed"); - return -1; - } - - if (certificates_loader::get_instance().load_certificates(_certificates, _hashed_id8s) == -1) { - loggers::get_instance().log(">>> security_db::load_from_files: certificates_loader::load_certificates method failed"); - return -1; - } - - return 0; -} - -int security_db::store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, - const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, const INTEGER &p_public_compressed_key_mode, - const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashed_id8, const OCTETSTRING &p_issuer, - const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, - const OCTETSTRING &p_public_enc_compressd_key, const INTEGER &p_public_enc_compressed_key_mode) { - loggers::get_instance().log_msg(">>> security_db::store_certificate: ", p_cert_id); - - if (security_cache::store_certificate(p_cert_id, p_cert, p_private_key, p_public_key_x, p_public_key_y, p_public_compressed_key, p_public_compressed_key_mode, - p_hash, p_hash_sha_256, p_hashed_id8, p_issuer, p_private_enc_key, p_public_enc_key_x, p_public_enc_key_y, - p_public_enc_compressd_key, p_public_enc_compressed_key_mode) != 0) { - return -1; - } - - std::map>::const_iterator it = _certificates.find(std::string(static_cast(p_cert_id))); - if (it == _certificates.cend()) { - loggers::get_instance().warning("security_db::get_certificate: record not found"); - return -1; - } - if (certificates_loader::get_instance().save_certificate(*it->second) == -1) { - return -1; - } - - return 0; -} +#include + +#include "security_db.hh" + +#include "params.hh" + +#include "converter.hh" + +using namespace std; // Required for isnan() +#include "certificates_loader.hh" + +#include "etsi_ts103097_certificate_codec.hh" + +#include "loggers.hh" + +security_db::security_db(const std::string &p_db_path) { + loggers::get_instance().log(">>> security_db::security_db: '%s'", p_db_path.c_str()); + + load_from_files(p_db_path); + dump(); +} // End of ctor + +security_db::~security_db() { loggers::get_instance().log(">>> security_db::~security_db"); } // End of dtor + +int security_db::load_from_files(const std::string &p_db_path) { + loggers::get_instance().log(">>> security_db::load_from_files: '%s'", p_db_path.c_str()); + + if (certificates_loader::get_instance().build_path(p_db_path) == -1) { + loggers::get_instance().log(">>> security_db::load_from_files: certificates_loader::build_path method failed"); + return -1; + } + + if (certificates_loader::get_instance().load_certificates(_certificates, _hashed_id8s) == -1) { + loggers::get_instance().log(">>> security_db::load_from_files: certificates_loader::load_certificates method failed"); + return -1; + } + + return 0; +} + +int security_db::store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, + const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, const INTEGER &p_public_compressed_key_mode, + const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashed_id8, const OCTETSTRING &p_issuer, + const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, + const OCTETSTRING &p_public_enc_compressd_key, const INTEGER &p_public_enc_compressed_key_mode) { + loggers::get_instance().log_msg(">>> security_db::store_certificate: ", p_cert_id); + + if (security_cache::store_certificate(p_cert_id, p_cert, p_private_key, p_public_key_x, p_public_key_y, p_public_compressed_key, p_public_compressed_key_mode, + p_hash, p_hash_sha_256, p_hashed_id8, p_issuer, p_private_enc_key, p_public_enc_key_x, p_public_enc_key_y, + p_public_enc_compressd_key, p_public_enc_compressed_key_mode) != 0) { + return -1; + } + + std::map>::const_iterator it = _certificates.find(std::string(static_cast(p_cert_id))); + if (it == _certificates.cend()) { + loggers::get_instance().warning("security_db::get_certificate: record not found"); + return -1; + } + if (certificates_loader::get_instance().save_certificate(*it->second) == -1) { + return -1; + } + + return 0; +} diff --git a/ccsrc/Protocols/Security/security_db.hh b/ccsrc/Protocols/Security/security_db.hh index a3943dbdb6eb4deb8f243e1282d531027ae47207..9ab98c96050a96b21fd3ed25e96b9167a044ac90 100644 --- a/ccsrc/Protocols/Security/security_db.hh +++ b/ccsrc/Protocols/Security/security_db.hh @@ -1,56 +1,56 @@ -/*! - * \file security_cache.hh - * \brief Header file for a certificates caching storage mechanism. - * It is used to store certificates received from neighbors and not present in the data base - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "security_cache.hh" - -class OCTETSTRING; //! TITAN forward declaration - -/*! - * \class security_db - * \brief This class provides security record description for security database - */ -class security_db : public security_cache { - -public: /*! \publicsection */ - /*! - * \brief Ctor with full path to the certificates storage - * \param[in] p_db_path The full path to the certificates storage - */ - security_db(const std::string &p_db_path); - /*! - * \brief Default dtor - */ - ~security_db(); - - /*! - * \fn int store_certificate(const CHARSTRING& p_cert_id, const OCTETSTRING& p_cert, const OCTETSTRING& p_private_key, const OCTETSTRING& p_public_key_x, - * const OCTETSTRING& p_public_key_y, const OCTETSTRING& p_public_compressed_key, const INTEGER& p_public_compressed_key_mode, const OCTETSTRING& p_hashid8, - * const OCTETSTRING& p_issuer, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_public_enc_key_x, const OCTETSTRING& p_public_enc_key_y, const - * OCTETSTRING& p_public_enc_compressed_key, const INTEGER& p_public_enc_compressed_key_mode); \brief Store a new certificate \param[in] p_cert_id The - * certificate identifier \return 0 on success, -1 otherwise - */ - int store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, - const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, const INTEGER &p_public_compressed_key_mode, - const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, - const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, - const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_compressed_key_mode); - -private: /*! \privatesection */ - /*! - * \fn int load_from_files(const std::string& p_db_path); - * \brief Initialise the storage of certificates mechanism - * \param[in] p_db_path The full path to the certificates storage - * \return 0 on success, -1 otherwise - */ - int load_from_files(const std::string &p_db_path); -}; // End of class security_db +/*! + * \file security_cache.hh + * \brief Header file for a certificates caching storage mechanism. + * It is used to store certificates received from neighbors and not present in the data base + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "security_cache.hh" + +class OCTETSTRING; //! TITAN forward declaration + +/*! + * \class security_db + * \brief This class provides security record description for security database + */ +class security_db : public security_cache { + +public: /*! \publicsection */ + /*! + * \brief Ctor with full path to the certificates storage + * \param[in] p_db_path The full path to the certificates storage + */ + security_db(const std::string &p_db_path); + /*! + * \brief Default dtor + */ + ~security_db(); + + /*! + * \fn int store_certificate(const CHARSTRING& p_cert_id, const OCTETSTRING& p_cert, const OCTETSTRING& p_private_key, const OCTETSTRING& p_public_key_x, + * const OCTETSTRING& p_public_key_y, const OCTETSTRING& p_public_compressed_key, const INTEGER& p_public_compressed_key_mode, const OCTETSTRING& p_hashid8, + * const OCTETSTRING& p_issuer, const OCTETSTRING& p_private_enc_key, const OCTETSTRING& p_public_enc_key_x, const OCTETSTRING& p_public_enc_key_y, const + * OCTETSTRING& p_public_enc_compressed_key, const INTEGER& p_public_enc_compressed_key_mode); \brief Store a new certificate \param[in] p_cert_id The + * certificate identifier \return 0 on success, -1 otherwise + */ + int store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, + const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_compressed_key, const INTEGER &p_public_compressed_key_mode, + const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, + const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, + const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_compressed_key_mode); + +private: /*! \privatesection */ + /*! + * \fn int load_from_files(const std::string& p_db_path); + * \brief Initialise the storage of certificates mechanism + * \param[in] p_db_path The full path to the certificates storage + * \return 0 on success, -1 otherwise + */ + int load_from_files(const std::string &p_db_path); +}; // End of class security_db diff --git a/ccsrc/Protocols/Security/security_db_record.cc b/ccsrc/Protocols/Security/security_db_record.cc index b3850235efca3077c5aa74528bf4c8e201e45dc5..3760651e03912290a230a14d81832781d5d0a63b 100644 --- a/ccsrc/Protocols/Security/security_db_record.cc +++ b/ccsrc/Protocols/Security/security_db_record.cc @@ -1,34 +1,34 @@ -/*! - * \file security_db_record.cc - * \brief Source file for a storage of certificates mechanism. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include "EtsiTs103097Module.hh" - -#include "security_db_record.hh" -#include "sha256.hh" -#include "sha384.hh" - -security_db_record::security_db_record(const std::string &p_certificate_id, const OCTETSTRING &p_certificate, - const Ieee1609Dot2::CertificateBase &p_decoded_certificate, const OCTETSTRING &p_hashed_id_issuer, - const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashed_id, - const OCTETSTRING &p_pr_key, const OCTETSTRING &p_pu_key_x, const OCTETSTRING &p_pu_key_y, - const OCTETSTRING &p_pu_comp_key, const OCTETSTRING &p_pr_enc_key, const OCTETSTRING &p_pu_enc_key_x, - const OCTETSTRING &p_pu_enc_key_y, const OCTETSTRING &p_pu_enc_comp_key, const bool p_to_be_saved) - : _algorithm{ec_elliptic_curves::nist_p_256}, _certificate_id(p_certificate_id), _certificate(p_certificate), _hashed_id_issuer(p_hashed_id_issuer), - _hash(p_hash), _hash_sha_256(p_hash_sha_256), _hashed_id(p_hashed_id), _pr_key(p_pr_key), _pu_key_x(p_pu_key_x), _pu_key_y(p_pu_key_y), - _pu_comp_key(p_pu_comp_key), _pr_enc_key(p_pr_enc_key), _pu_enc_key_x(p_pu_enc_key_x), _pu_enc_key_y(p_pu_enc_key_y), _pu_enc_comp_key(p_pu_enc_comp_key), - _to_be_saved(p_to_be_saved), _decoded_certificate(static_cast(p_decoded_certificate.clone())) {} - -security_db_record::~security_db_record() { - if (_decoded_certificate != nullptr) { - delete _decoded_certificate; - } -}; - -const Ieee1609Dot2::CertificateBase &security_db_record::decoded_certificate() const { return *_decoded_certificate; } +/*! + * \file security_db_record.cc + * \brief Source file for a storage of certificates mechanism. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include "EtsiTs103097Module.hh" + +#include "security_db_record.hh" +#include "sha256.hh" +#include "sha384.hh" + +security_db_record::security_db_record(const std::string &p_certificate_id, const OCTETSTRING &p_certificate, + const Ieee1609Dot2::CertificateBase &p_decoded_certificate, const OCTETSTRING &p_hashed_id_issuer, + const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashed_id, + const OCTETSTRING &p_pr_key, const OCTETSTRING &p_pu_key_x, const OCTETSTRING &p_pu_key_y, + const OCTETSTRING &p_pu_comp_key, const OCTETSTRING &p_pr_enc_key, const OCTETSTRING &p_pu_enc_key_x, + const OCTETSTRING &p_pu_enc_key_y, const OCTETSTRING &p_pu_enc_comp_key, const bool p_to_be_saved) + : _algorithm{ec_elliptic_curves::nist_p_256}, _certificate_id(p_certificate_id), _certificate(p_certificate), _hashed_id_issuer(p_hashed_id_issuer), + _hash(p_hash), _hash_sha_256(p_hash_sha_256), _hashed_id(p_hashed_id), _pr_key(p_pr_key), _pu_key_x(p_pu_key_x), _pu_key_y(p_pu_key_y), + _pu_comp_key(p_pu_comp_key), _pr_enc_key(p_pr_enc_key), _pu_enc_key_x(p_pu_enc_key_x), _pu_enc_key_y(p_pu_enc_key_y), _pu_enc_comp_key(p_pu_enc_comp_key), + _to_be_saved(p_to_be_saved), _decoded_certificate(static_cast(p_decoded_certificate.clone())) {} + +security_db_record::~security_db_record() { + if (_decoded_certificate != nullptr) { + delete _decoded_certificate; + } +}; + +const Ieee1609Dot2::CertificateBase &security_db_record::decoded_certificate() const { return *_decoded_certificate; } diff --git a/ccsrc/Protocols/Security/security_db_record.hh b/ccsrc/Protocols/Security/security_db_record.hh index ef8534ec3a45934c98ed7c51b8ace337a518f304..94fb41297d03bf2b8355303d9bca1422ed1d3f8d 100644 --- a/ccsrc/Protocols/Security/security_db_record.hh +++ b/ccsrc/Protocols/Security/security_db_record.hh @@ -1,136 +1,136 @@ -/*! - * \file security_db_record.hh - * \brief Header file for a storage of certificates mechanism. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "security_ecc.hh" - -class OCTETSTRING; //! TITAN forward declaration - -namespace Ieee1609Dot2 { - class CertificateBase; -}; - -/*! - * \class security_db_record - * \brief This class provides security record description for security database - */ -class security_db_record { - - ec_elliptic_curves _algorithm; /*!< Signature . Default: nist_p_256 */ - std::string _certificate_id; /*!< Certificate storage*/ - OCTETSTRING _certificate; /*!< COER storage */ - OCTETSTRING _hashed_id_issuer; /*!< Hash id 8 of the issuer certificate */ - OCTETSTRING _hash; /*!< Certificate hash storage */ - OCTETSTRING _hash_sha_256; /*!< Certificate hash SHA 256 storage, for encryption (IEEE 1609.2 Clause 5.3.5 Public key encryption algorithms: ECIES */ - OCTETSTRING _hashed_id; /*!< Certificate hash id 8 storage */ - OCTETSTRING _pr_key; /*!< Private key storage */ - OCTETSTRING _pu_key_x; /*!< Public key X-coordinate storage */ - OCTETSTRING _pu_key_y; /*!< Public key Y-coordinate storage */ - OCTETSTRING _pu_comp_key; /*!< Public compressed key storage */ - OCTETSTRING _pr_enc_key; /*!< Private encryption key storage */ - OCTETSTRING _pu_enc_key_x; /*!< Public encryption key X-coordinate storage */ - OCTETSTRING _pu_enc_key_y; /*!< Public encryption key Y-coordinate storage */ - OCTETSTRING _pu_enc_comp_key; /*!< Public compressed encryption key storage */ - bool _to_be_saved; /*!< Flag to indicate if the record shall be saved, i.e. has been modified */ - Ieee1609Dot2::CertificateBase *_decoded_certificate; - -public: /*! \publicsection */ - /*! - * \brief Default ctor - */ - explicit security_db_record() - : _algorithm{ec_elliptic_curves::nist_p_256}, _certificate_id(), _certificate(), _hashed_id_issuer(), _hash(), _hash_sha_256(), _hashed_id(), _pr_key(), - _pu_key_x(), _pu_key_y(), _pu_comp_key(), _pr_enc_key(), _pu_enc_key_x(), _pu_enc_key_y(), _pu_enc_comp_key(), _to_be_saved(false), - _decoded_certificate(nullptr){}; - /*! - * \brief Specialised ctor - * \param[in] p_certificate_id The certificate identifier - * \param[in] p_certificate The COER encoded certificate - * \param[in] p_decoded_certificate The decoded certificate - * \param[in] p_hashed_id_issuer The HashedId of the certificate issuer - * \param[in] p_hash The whole-certificate hash - * \param[in] p_hash_sha_256 The whole-certificate hash using SHA-256 - * \param[in] p_hashed_id The whole-certificate hashed id - * \param[in] p_pr_key The private signature key - * \param[in] p_pu_key_x The public X-coordinate signature key - * \param[in] p_pu_key_y The public Y-coordinate signature key - * \param[in] p_pu_comp_key The public compressed coordinate signature key - * \param[in] p_pr_enc_key The private encryption key - * \param[in] p_pu_enc_key_x The public X-coordinate encryption key - * \param[in] p_pu_enc_key_y The public Y-coordinate encryption key - * \param[in] p_pu_enc_comp_key_y The public compressed coordinate encryption key - * \param[in] p_to_be_saved Set to true to save on disk this certificate.Default: true - */ - security_db_record(const std::string &p_certificate_id, const OCTETSTRING &p_certificate, const Ieee1609Dot2::CertificateBase &p_decoded_certificate, - const OCTETSTRING &p_hashed_id_issuer, const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashed_id, - const OCTETSTRING &p_pr_key, const OCTETSTRING &p_pu_key_x, const OCTETSTRING &p_pu_key_y, const OCTETSTRING &p_pu_comp_key, - const OCTETSTRING &p_pr_enc_key, const OCTETSTRING &p_pu_enc_key_x, const OCTETSTRING &p_pu_enc_key_y, - const OCTETSTRING &p_pu_enc_comp_key_y, const bool p_to_be_saved = true); - - /*! - * \brief Default dtor - */ - ~security_db_record(); - - /*! - * \fn const Ieee1609Dot2::CertificateBase& decoded_certificate() const; - * \brief Retrieve the decoded certificate value - * \return The decoded certificate - */ - const Ieee1609Dot2::CertificateBase &decoded_certificate() const; - - /*! - * \inline - * \fn const std::string& certificate_id() const; - * \brief Retrieve the certificate identifier value - * \return The certificate identifier - */ - inline const std::string &certificate_id() const { return _certificate_id; }; - /*! - * \inline - * \fn const OCTETSTRING& certificate() const; - * \brief Retrieve the COER encoded certificate - * \return The COER encoded certificate - */ - inline const OCTETSTRING &certificate() const { return _certificate; }; - /*! - * \inline - * \fn const OCTETSTRING& hashed_id() const; - * \brief Retrieve the HashedId of the certificate issuer - * \return The HashedId of the certificate issuer - */ - inline const OCTETSTRING &hashed_id() const { return _hashed_id; }; - /*! - * \inline - * \fn const OCTETSTRING& hash() const; - * \brief Retrieve the whole-certificate hashed id - * \return The whole-certificate hashed id - */ - inline const OCTETSTRING &hash() const { return _hash; }; - /*! - * \inline - * \fn const OCTETSTRING& hash_sha_256() const; - * \brief Retrieve the whole-certificate hashed id - * \return The whole-certificate hashed id - */ - inline const OCTETSTRING &hash_sha_256() const { return _hash_sha_256; }; - inline const OCTETSTRING &issuer() const { return _hashed_id_issuer; }; - inline const OCTETSTRING &private_key() const { return _pr_key; }; - inline const OCTETSTRING &public_key_x() const { return _pu_key_x; }; - inline const OCTETSTRING &public_key_y() const { return _pu_key_y; }; - inline const OCTETSTRING &public_comp_key() const { return _pu_comp_key; }; - inline const OCTETSTRING &private_enc_key() const { return _pr_enc_key; }; - inline const OCTETSTRING &public_enc_key_x() const { return _pu_enc_key_x; }; - inline const OCTETSTRING &public_enc_key_y() const { return _pu_enc_key_y; }; - inline const OCTETSTRING &public_enc_comp_key() const { return _pu_enc_comp_key; }; -}; // End of class security_db_record +/*! + * \file security_db_record.hh + * \brief Header file for a storage of certificates mechanism. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "security_ecc.hh" + +class OCTETSTRING; //! TITAN forward declaration + +namespace Ieee1609Dot2 { + class CertificateBase; +}; + +/*! + * \class security_db_record + * \brief This class provides security record description for security database + */ +class security_db_record { + + ec_elliptic_curves _algorithm; /*!< Signature . Default: nist_p_256 */ + std::string _certificate_id; /*!< Certificate storage*/ + OCTETSTRING _certificate; /*!< COER storage */ + OCTETSTRING _hashed_id_issuer; /*!< Hash id 8 of the issuer certificate */ + OCTETSTRING _hash; /*!< Certificate hash storage */ + OCTETSTRING _hash_sha_256; /*!< Certificate hash SHA 256 storage, for encryption (IEEE 1609.2 Clause 5.3.5 Public key encryption algorithms: ECIES */ + OCTETSTRING _hashed_id; /*!< Certificate hash id 8 storage */ + OCTETSTRING _pr_key; /*!< Private key storage */ + OCTETSTRING _pu_key_x; /*!< Public key X-coordinate storage */ + OCTETSTRING _pu_key_y; /*!< Public key Y-coordinate storage */ + OCTETSTRING _pu_comp_key; /*!< Public compressed key storage */ + OCTETSTRING _pr_enc_key; /*!< Private encryption key storage */ + OCTETSTRING _pu_enc_key_x; /*!< Public encryption key X-coordinate storage */ + OCTETSTRING _pu_enc_key_y; /*!< Public encryption key Y-coordinate storage */ + OCTETSTRING _pu_enc_comp_key; /*!< Public compressed encryption key storage */ + bool _to_be_saved; /*!< Flag to indicate if the record shall be saved, i.e. has been modified */ + Ieee1609Dot2::CertificateBase *_decoded_certificate; + +public: /*! \publicsection */ + /*! + * \brief Default ctor + */ + explicit security_db_record() + : _algorithm{ec_elliptic_curves::nist_p_256}, _certificate_id(), _certificate(), _hashed_id_issuer(), _hash(), _hash_sha_256(), _hashed_id(), _pr_key(), + _pu_key_x(), _pu_key_y(), _pu_comp_key(), _pr_enc_key(), _pu_enc_key_x(), _pu_enc_key_y(), _pu_enc_comp_key(), _to_be_saved(false), + _decoded_certificate(nullptr){}; + /*! + * \brief Specialised ctor + * \param[in] p_certificate_id The certificate identifier + * \param[in] p_certificate The COER encoded certificate + * \param[in] p_decoded_certificate The decoded certificate + * \param[in] p_hashed_id_issuer The HashedId of the certificate issuer + * \param[in] p_hash The whole-certificate hash + * \param[in] p_hash_sha_256 The whole-certificate hash using SHA-256 + * \param[in] p_hashed_id The whole-certificate hashed id + * \param[in] p_pr_key The private signature key + * \param[in] p_pu_key_x The public X-coordinate signature key + * \param[in] p_pu_key_y The public Y-coordinate signature key + * \param[in] p_pu_comp_key The public compressed coordinate signature key + * \param[in] p_pr_enc_key The private encryption key + * \param[in] p_pu_enc_key_x The public X-coordinate encryption key + * \param[in] p_pu_enc_key_y The public Y-coordinate encryption key + * \param[in] p_pu_enc_comp_key_y The public compressed coordinate encryption key + * \param[in] p_to_be_saved Set to true to save on disk this certificate.Default: true + */ + security_db_record(const std::string &p_certificate_id, const OCTETSTRING &p_certificate, const Ieee1609Dot2::CertificateBase &p_decoded_certificate, + const OCTETSTRING &p_hashed_id_issuer, const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashed_id, + const OCTETSTRING &p_pr_key, const OCTETSTRING &p_pu_key_x, const OCTETSTRING &p_pu_key_y, const OCTETSTRING &p_pu_comp_key, + const OCTETSTRING &p_pr_enc_key, const OCTETSTRING &p_pu_enc_key_x, const OCTETSTRING &p_pu_enc_key_y, + const OCTETSTRING &p_pu_enc_comp_key_y, const bool p_to_be_saved = true); + + /*! + * \brief Default dtor + */ + ~security_db_record(); + + /*! + * \fn const Ieee1609Dot2::CertificateBase& decoded_certificate() const; + * \brief Retrieve the decoded certificate value + * \return The decoded certificate + */ + const Ieee1609Dot2::CertificateBase &decoded_certificate() const; + + /*! + * \inline + * \fn const std::string& certificate_id() const; + * \brief Retrieve the certificate identifier value + * \return The certificate identifier + */ + inline const std::string &certificate_id() const { return _certificate_id; }; + /*! + * \inline + * \fn const OCTETSTRING& certificate() const; + * \brief Retrieve the COER encoded certificate + * \return The COER encoded certificate + */ + inline const OCTETSTRING &certificate() const { return _certificate; }; + /*! + * \inline + * \fn const OCTETSTRING& hashed_id() const; + * \brief Retrieve the HashedId of the certificate issuer + * \return The HashedId of the certificate issuer + */ + inline const OCTETSTRING &hashed_id() const { return _hashed_id; }; + /*! + * \inline + * \fn const OCTETSTRING& hash() const; + * \brief Retrieve the whole-certificate hashed id + * \return The whole-certificate hashed id + */ + inline const OCTETSTRING &hash() const { return _hash; }; + /*! + * \inline + * \fn const OCTETSTRING& hash_sha_256() const; + * \brief Retrieve the whole-certificate hashed id + * \return The whole-certificate hashed id + */ + inline const OCTETSTRING &hash_sha_256() const { return _hash_sha_256; }; + inline const OCTETSTRING &issuer() const { return _hashed_id_issuer; }; + inline const OCTETSTRING &private_key() const { return _pr_key; }; + inline const OCTETSTRING &public_key_x() const { return _pu_key_x; }; + inline const OCTETSTRING &public_key_y() const { return _pu_key_y; }; + inline const OCTETSTRING &public_comp_key() const { return _pu_comp_key; }; + inline const OCTETSTRING &private_enc_key() const { return _pr_enc_key; }; + inline const OCTETSTRING &public_enc_key_x() const { return _pu_enc_key_x; }; + inline const OCTETSTRING &public_enc_key_y() const { return _pu_enc_key_y; }; + inline const OCTETSTRING &public_enc_comp_key() const { return _pu_enc_comp_key; }; +}; // End of class security_db_record diff --git a/ccsrc/Protocols/Security/security_ecc.cc b/ccsrc/Protocols/Security/security_ecc.cc index 955852f2435f9b264a4952e929ede2cce577a1f9..e0f7d6b94e15a481b27e05f82bd7fb0654ad8c0a 100644 --- a/ccsrc/Protocols/Security/security_ecc.cc +++ b/ccsrc/Protocols/Security/security_ecc.cc @@ -1,993 +1,993 @@ -/*! - * \file security_ecc.cc - * \brief Source file for Elliptic Curve Cryptography. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include - -#include -#include - -#include "sha256.hh" - -#include "hmac.hh" -#include "security_ecc.hh" - -#include "loggers.hh" - -#if OPENSSL_VERSION_NUMBER >= 0x10101000L -#define EC_POINT_get_affine_coordinates_GFp EC_POINT_get_affine_coordinates -#define EC_POINT_get_affine_coordinates_GF2m EC_POINT_get_affine_coordinates -#define EC_POINT_set_affine_coordinates_GFp EC_POINT_set_affine_coordinates -#define EC_POINT_set_affine_coordinates_GF2m EC_POINT_set_affine_coordinates -#define EC_POINT_set_compressed_coordinates_GFp EC_POINT_set_compressed_coordinates -#define EC_POINT_set_compressed_coordinates_GF2m EC_POINT_set_compressed_coordinates -#endif - -security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve) - : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), - _pri_key(), _pub_key_x(), _pub_key_y(), _pub_key_compressed(), _pub_key_compressed_mode{ecc_compressed_mode::compressed_y_0}, _secret_key(), _enc_key_x(), - _enc_key_y(), _sym_key(), _nonce(), _tag() { - loggers::get_instance().log(">>> security_ecc::security_ecc: %d", static_cast(p_elliptic_curve)); - - const int result = init(); - if (result == -1) { - loggers::get_instance().error("security_ecc::security_ecc: Unsupported elliptic_curve %d", _elliptic_curve); - } -} // End of constructor - -security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_private_key) - : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), - _pri_key(p_private_key), _pub_key_x(), _pub_key_y(), _pub_key_compressed(), _pub_key_compressed_mode{ecc_compressed_mode::compressed_y_0}, _secret_key(), - _enc_key_x(), _enc_key_y(), _sym_key(), _nonce(), _tag() { - loggers::get_instance().log(">>> security_ecc::security_ecc (1): %d", static_cast(p_elliptic_curve)); - - // Sanity checks - if ((_elliptic_curve == ec_elliptic_curves::nist_p_256) || (_elliptic_curve == ec_elliptic_curves::brainpool_p_256_r1)) { - if (p_private_key.lengthof() != 32) { - loggers::get_instance().error("security_ecc::security_ecc (1): Invalid public keys size"); - } - } else if (_elliptic_curve == ec_elliptic_curves::brainpool_p_384_r1) { - if ((p_private_key.lengthof() != 48)) { - loggers::get_instance().error("security_ecc::security_ecc (1): Invalid public keys size"); - } - } - - int result = init(); - if (result == -1) { - loggers::get_instance().error("security_ecc::security_ecc (1): Unsupported elliptic_curve %d", _elliptic_curve); - } - ::EC_KEY_set_conv_form(_ec_key, POINT_CONVERSION_UNCOMPRESSED); - - // Build private key - BIGNUM *p = ::BN_new(); - ::BN_bin2bn(static_cast(_pri_key), _pri_key.lengthof(), p); - // Build public keys - EC_POINT *ec_point = ::EC_POINT_new(_ec_group); - ::EC_POINT_mul(_ec_group, ec_point, p, nullptr, nullptr, _bn_ctx); - // Set private key - ::EC_KEY_set_private_key(_ec_key, p); - if (::EC_KEY_check_key(_ec_key) != 0) { - ::BN_clear_free(p); - loggers::get_instance().error("security_ecc::security_ecc (1): Invalid private key"); - } - ::BN_clear_free(p); - p = nullptr; - // Private key is correct, set public keys - ::EC_KEY_set_public_key(_ec_key, ec_point); - - BIGNUM *xy = ::BN_new(); - ::EC_POINT_point2bn(_ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, xy, _bn_ctx); - if (BN_num_bytes(xy) == 0) { - ::BN_clear_free(xy); - loggers::get_instance().error("security_ecc::security_ecc (1): Failed to generate xy coordinates, check algorithms"); - } - loggers::get_instance().log("security_ecc::security_ecc (1): xy length: %d", BN_num_bytes(xy)); - OCTETSTRING v = int2oct(0, BN_num_bytes(xy)); - ::BN_bn2bin(xy, (unsigned char *)static_cast(v)); - if ((v.lengthof() % 2) != 0) { - // Remove first byte - loggers::get_instance().log_msg("security_ecc::security_ecc (1): Complete xy=", v); - v = OCTETSTRING(v.lengthof() - 1, 1 + static_cast(v)); - } - ::BN_clear_free(xy); - xy = nullptr; - - loggers::get_instance().log_msg("security_ecc::security_ecc (1): xy=", v); - const int l = v.lengthof() / 2; - _pub_key_x = OCTETSTRING(l, static_cast(v)); - _pub_key_y = OCTETSTRING(l, l + static_cast(v)); - - // Compressed - int len = ::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, nullptr, 0, _bn_ctx); - if (len == 0) { - loggers::get_instance().warning("security_ecc::security_ecc (1): Failed to generate x_coordinate compressed key"); - _pub_key_compressed = OCTETSTRING(0, nullptr); - } else { - _pub_key_compressed = int2oct(0, len); - if (::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, (unsigned char *)static_cast(_pub_key_compressed), len, - _bn_ctx) == 0) { - loggers::get_instance().warning("security_ecc::security_ecc (1): Failed to generate x_coordinate compressed key"); - _pub_key_compressed = OCTETSTRING(0, nullptr); - } else { // Remove first byte - loggers::get_instance().log_msg("security_ecc::security_ecc (1): Complete _pub_key_compressed=", _pub_key_compressed); - _pub_key_compressed_mode = ((v[0].get_octet() & 0x01) == 0x00) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1; - _pub_key_compressed = OCTETSTRING(_pub_key_compressed.lengthof() - 1, 1 + static_cast(_pub_key_compressed)); - } - } - ::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); - loggers::get_instance().log("security_ecc::security_ecc (1): _pub_key_compressed_mode=%d", _pub_key_compressed_mode); -} // End of constructor - -security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y) - : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), - _pri_key(), _pub_key_x(p_public_key_x), _pub_key_y(p_public_key_y), _pub_key_compressed(), _pub_key_compressed_mode{ecc_compressed_mode::compressed_y_0}, - _secret_key(), _enc_key_x(), _enc_key_y(), _sym_key(), _nonce(), _tag() { - loggers::get_instance().log(">>> security_ecc::security_ecc (2): %d", static_cast(p_elliptic_curve)); - - // Sanity checks - if ((_elliptic_curve == ec_elliptic_curves::nist_p_256) || (_elliptic_curve == ec_elliptic_curves::brainpool_p_256_r1)) { - if ((p_public_key_x.lengthof() != 32) || (p_public_key_y.lengthof() != 32)) { - loggers::get_instance().error("security_ecc::security_ecc (2): Invalid public keys size"); - } - } else if (_elliptic_curve == ec_elliptic_curves::brainpool_p_384_r1) { - if ((p_public_key_x.lengthof() != 48) || (p_public_key_y.lengthof() != 48)) { - loggers::get_instance().error("security_ecc::security_ecc (2): Invalid public keys size"); - } - } - - int result = init(); - if (result == -1) { - loggers::get_instance().error("security_ecc::security_ecc (2): Unsupported elliptic_curve %d", _elliptic_curve); - } - ::EC_KEY_set_conv_form(_ec_key, POINT_CONVERSION_UNCOMPRESSED); - - // Set public key - BIGNUM *x = ::BN_new(); - ::BN_bin2bn(static_cast(_pub_key_x), _pub_key_x.lengthof(), x); - BIGNUM *y = ::BN_new(); - ::BN_bin2bn(static_cast(_pub_key_y), _pub_key_y.lengthof(), y); - EC_POINT *ec_point = ::EC_POINT_new(_ec_group); - result = 0; - switch (_elliptic_curve) { - case ec_elliptic_curves::nist_p_256: // Use primary - // No break; - case ec_elliptic_curves::brainpool_p_256_r1: - // No break; - case ec_elliptic_curves::brainpool_p_384_r1: - result = ::EC_POINT_set_affine_coordinates_GFp(_ec_group, ec_point, x, y, _bn_ctx); // Use primary elliptic curve - break; - default: // Use Binary - result = 0; // FIXME Does not compile on Windows ::EC_POINT_set_affine_coordinates_GF2m(_ec_group, ec_point, x, y, _bn_ctx); - } // End of 'switch' statement - if (result == 0) { - ::BN_clear_free(x); - ::BN_clear_free(y); - loggers::get_instance().error("security_ecc::security_ecc (2): Failed to get coordinates"); - } - ::BN_clear_free(x); - x = nullptr; - ::BN_clear_free(y); - y = nullptr; - - ::EC_KEY_set_public_key(_ec_key, ec_point); - - // Compressed - int len = ::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, nullptr, 0, _bn_ctx); - if (len == 0) { - loggers::get_instance().warning("security_ecc::security_ecc (2): Failed to generate x_coordinate compressed key"); - } - _pub_key_compressed = int2oct(0, len); - if (::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, (unsigned char *)static_cast(_pub_key_compressed), len, - _bn_ctx) == 0) { - loggers::get_instance().warning("security_ecc::security_ecc (2): Failed to generate x_coordinate compressed key"); - _pub_key_compressed = OCTETSTRING(0, nullptr); - } else { // Remove first byte - loggers::get_instance().log_msg("security_ecc::security_ecc (2): Complete _pub_key_compressed=", _pub_key_compressed); - _pub_key_compressed = OCTETSTRING(_pub_key_compressed.lengthof() - 1, 1 + static_cast(_pub_key_compressed)); - } - ::EC_POINT_free(ec_point); - loggers::get_instance().log_msg("security_ecc::security_ecc (2): _pub_key_x=", _pub_key_x); - loggers::get_instance().log_msg("security_ecc::security_ecc (2): _pub_key_y=", _pub_key_y); - loggers::get_instance().log_msg("security_ecc::security_ecc (2): _pub_key_compressed=", _pub_key_compressed); - loggers::get_instance().log("security_ecc::security_ecc (2): _pub_key_compressed_mode=%d", _pub_key_compressed_mode); -} // End of constructor - -security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_compressed, const ecc_compressed_mode p_compressed_mode) - : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), - _pri_key(), _pub_key_x(), _pub_key_y(), _pub_key_compressed(p_public_key_compressed), _pub_key_compressed_mode{p_compressed_mode}, _secret_key(), - _enc_key_x(), _enc_key_y(), _sym_key(), _nonce(), _tag() { - loggers::get_instance().log(">>> security_ecc::security_ecc (3): %d", static_cast(p_elliptic_curve)); - - // Sanity checks - if ((_elliptic_curve == ec_elliptic_curves::nist_p_256) || (_elliptic_curve == ec_elliptic_curves::brainpool_p_256_r1)) { - if (p_public_key_compressed.lengthof() != 32) { - loggers::get_instance().error("security_ecc::security_ecc (3): Invalid public keys size"); - } - } else if (_elliptic_curve == ec_elliptic_curves::brainpool_p_384_r1) { - if (p_public_key_compressed.lengthof() != 48) { - loggers::get_instance().error("security_ecc::security_ecc (3): Invalid public keys size"); - } - } - - int result = init(); - if (result == -1) { - loggers::get_instance().error("security_ecc::security_ecc (3): Unsupported elliptic_curve %d", _elliptic_curve); - } - ::EC_KEY_set_conv_form(_ec_key, POINT_CONVERSION_UNCOMPRESSED); - - // Set public key - BIGNUM *compressed_key = ::BN_new(); - ::BN_bin2bn(static_cast(_pub_key_compressed), _pub_key_compressed.lengthof(), compressed_key); - EC_POINT *ec_point = ::EC_POINT_new(_ec_group); - result = 0; - switch (_elliptic_curve) { - case ec_elliptic_curves::nist_p_256: // Use primary - // No break; - case ec_elliptic_curves::brainpool_p_256_r1: - // No break; - case ec_elliptic_curves::brainpool_p_384_r1: - result = ::EC_POINT_set_compressed_coordinates_GFp( - _ec_group, ec_point, compressed_key, (p_compressed_mode == ecc_compressed_mode::compressed_y_1) ? 1 : 0, _bn_ctx); // Use primary elliptic curve - break; - default: // Use Binary - result = 0; // FIXME Does not compile on Windows ::EC_POINT_set_compressed_coordinates_GF2m(_ec_group, ec_point, compressed_key, (p_compressed_mode == - // ecc_compressed_mode::compressed_y_1) ? 1 : 0, _bn_ctx); - } // End of 'switch' statement - BN_clear_free(compressed_key); - compressed_key = nullptr; - - if (result == 0) { - loggers::get_instance().error("security_ecc::security_ecc (3): Failed to get coordinates"); - } else if (::EC_POINT_is_on_curve(_ec_group, ec_point, _bn_ctx) == 0) { - loggers::get_instance().error("security_ecc::security_ecc (3): Point Y0 is not on the curve"); - } - - // Set public keys - BIGNUM *xy = ::BN_new(); - ::EC_POINT_point2bn(_ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, xy, _bn_ctx); - if (BN_num_bytes(xy) == 0) { - ::BN_clear_free(xy); - loggers::get_instance().error("security_ecc::security_ecc (3): Failed to generate xy coordinates, check algorithms"); - } - loggers::get_instance().log("security_ecc::security_ecc (3): xy length: %d", BN_num_bytes(xy)); - ::EC_KEY_set_public_key(_ec_key, ec_point); - // Generate X, Y coordinates - OCTETSTRING v = int2oct(0, BN_num_bytes(xy)); - ::BN_bn2bin(xy, (unsigned char *)static_cast(v)); - ::BN_clear_free(xy); - xy = nullptr; - if ((v.lengthof() % 2) != 0) { // TODO Check alse xy[0] == 0x04 - // Remove first byte - loggers::get_instance().log_msg("security_ecc::security_ecc (3): Complete xy=", v); - v = OCTETSTRING(v.lengthof() - 1, 1 + static_cast(v)); - } - loggers::get_instance().log_msg("security_ecc::security_ecc (3): xy=", v); - const int l = v.lengthof() / 2; - _pub_key_x = OCTETSTRING(l, static_cast(v)); - _pub_key_y = OCTETSTRING(l, l + static_cast(v)); - ::EC_POINT_free(ec_point); - - loggers::get_instance().log_msg("security_ecc::security_ecc (3): _pub_key_x=", _pub_key_x); - loggers::get_instance().log_msg("security_ecc::security_ecc (3): _pub_key_y=", _pub_key_y); - loggers::get_instance().log_msg("security_ecc::security_ecc (3): _pub_key_compressed=", _pub_key_compressed); - loggers::get_instance().log("security_ecc::security_ecc (3): _pub_key_compressed_mode=%d", _pub_key_compressed_mode); -} // End of constructor - -security_ecc::~security_ecc() { - loggers::get_instance().log(">>> security_ecc::~security_ecc"); - - if (_ec_key != nullptr) { - ::EC_KEY_free(_ec_key); - } - if (_bn_ctx != nullptr) { - ::BN_CTX_free(_bn_ctx); - } - - loggers::get_instance().log("<<< security_ecc::~security_ecc"); -} // End of Destructor - -int security_ecc::generate() { - loggers::get_instance().log(">>> security_ecc::generate"); - - // Sanity check - if (!::EC_KEY_generate_key(_ec_key)) { // Generate the private and public keys - loggers::get_instance().error("security_ecc::generate: Failed to generate private/public keys"); - return -1; - } - - BIGNUM * x = ::BN_new(); - BIGNUM * y = ::BN_new(); - const EC_POINT *ec_point = EC_KEY_get0_public_key(_ec_key); - int result = 0; - int size = 0; - switch (_elliptic_curve) { - case ec_elliptic_curves::nist_p_256: // Use primary - // No break; - case ec_elliptic_curves::brainpool_p_256_r1: - size = 32; - result = ::EC_POINT_get_affine_coordinates_GFp(_ec_group, ec_point, x, y, _bn_ctx); // Use primer on elliptic curve - break; - case ec_elliptic_curves::brainpool_p_384_r1: - size = 48; - result = ::EC_POINT_get_affine_coordinates_GFp(_ec_group, ec_point, x, y, _bn_ctx); // Use primer on elliptic curve - break; - default: // Use binary - result = 0; // FIXME Does not compile on Windows ::EC_POINT_get_affine_coordinates_GF2m(_ec_group, ec_point, x, y, _bn_ctx); - } // End of 'switch' statement - if (result == 0) { - loggers::get_instance().error("security_ecc::generate: Failed to get coordinates"); - } - const BIGNUM *p = ::EC_KEY_get0_private_key(_ec_key); - - _pri_key = int2oct(0, size); - ::BN_bn2bin(p, (unsigned char *)static_cast(_pri_key)); - _pub_key_x = int2oct(0, size); - ::BN_bn2bin(x, (unsigned char *)static_cast(_pub_key_x)); - _pub_key_y = int2oct(0, size); - ::BN_bn2bin(y, (unsigned char *)static_cast(_pub_key_y)); - ::BN_clear_free(x); - x = nullptr; - ::BN_clear_free(y); - y = nullptr; - - // Compressed - int len = ::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, nullptr, 0, _bn_ctx); - if (len == 0) { - loggers::get_instance().warning("security_ecc::generate: Failed to generate x_coordinate compressed key"); - } - _pub_key_compressed = int2oct(0, len); - if (::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, (unsigned char *)static_cast(_pub_key_compressed), len, - _bn_ctx) == 0) { - loggers::get_instance().warning("security_ecc::generate: Failed to generate x_coordinate compressed key"); - _pub_key_compressed = OCTETSTRING(0, nullptr); - } else { // Remove first byte - loggers::get_instance().log_msg("security_ecc::generate: Complete _pub_key_compressed=", _pub_key_compressed); - _pub_key_compressed_mode = - ((_pub_key_compressed[0].get_octet() & 0x01) == 0x00) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1; - _pub_key_compressed = OCTETSTRING(_pub_key_compressed.lengthof() - 1, 1 + static_cast(_pub_key_compressed)); - } - loggers::get_instance().log_msg("security_ecc::generate: _pri_key=", _pri_key); - loggers::get_instance().log_msg("security_ecc::generate: _pub_key_x=", _pub_key_x); - loggers::get_instance().log_msg("security_ecc::generate: _pub_key_y=", _pub_key_y); - loggers::get_instance().log_msg("security_ecc::generate: _pub_key_compressed=", _pub_key_compressed); - loggers::get_instance().log("security_ecc::generate: _pub_key_compressed_mode=%d", _pub_key_compressed_mode); - - 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, 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) { - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Key shall be generated"); - return -1; - } - if ((_pub_key_x.lengthof() == 0) || (_pub_key_y.lengthof() == 0)) { - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Keys shall be generated"); - return -1; - } - _encryption_algotithm = p_enc_algorithm; - - // 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; - unsigned int tag_length; - switch (_encryption_algotithm) { - case encryption_algotithm::aes_128_ccm: - // No break; - case encryption_algotithm::aes_128_gcm: - nonce_length = 12; - sym_key_length = 16; - tag_length = 16; - break; - default: - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Unsupported encryption algorithm"); - return -1; - } // End of 'switch' statement - 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_enc = 16; - k_mac = 32; - break; - case ec_elliptic_curves::brainpool_p_384_r1: - 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"); - return -1; - } // End of 'switch' statement - - // 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 (Key Agreement) - int result = ::ECDH_compute_key((unsigned char *)static_cast(_secret_key), _secret_key.lengthof(), - ec_point, // From recipient's public key - _ec_key, // From ephemeral's private key - nullptr); - if (result != _secret_key.lengthof()) { - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Failed to generate shared secret key"); - ::EC_POINT_free(ec_point); - return -1; - } - ::EC_POINT_free(ec_point); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _secret_key: ", _secret_key); - - // Derive the shared secret key - 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 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, nonce_length * 8, -1, 0); - _nonce = int2oct(0, nonce_length); - ::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_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 ((_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; - _tag = p_authentication_vector; - - // 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; - unsigned int tag_length; - switch (_encryption_algotithm) { - case encryption_algotithm::aes_128_ccm: - // No break; - case encryption_algotithm::aes_128_gcm: - nonce_length = 12; - sym_key_length = 16; - tag_length = 16; - break; - default: - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Unsupported encryption algorithm"); - return -1; - } // End of 'switch' statement - 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_enc = 16; - k_mac = 32; - break; - case ec_elliptic_curves::brainpool_p_384_r1: - break; - default: - loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Unsupported encryption algorithm"); - return -1; - } // 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(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, // From recipient's private key - _ec_key, // From sender's public key - nullptr); - if (result != _secret_key.lengthof()) { - 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; - } - ::EC_POINT_free(ec_point); - loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): _secret_key: ", _secret_key); - - // Derive the shared secret key - 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 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::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)) { - loggers::get_instance().warning("security_ecc::encrypt: Constructor format #1 shall be used"); - return -1; - } - _encryption_algotithm = p_enc_algorithm; - - // 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); - // 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_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 - ::RAND_bytes((unsigned char *)static_cast(_sym_key), _sym_key.lengthof()); - loggers::get_instance().log_msg("security_ecc::encrypt: _sym_key: ", _sym_key); - // Generate _nonce - ::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, ctr_set_iv_len, _nonce.lengthof(), nullptr); - // Set tag length - ::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 - // Encrypt the data - int len = 0; - ::EVP_EncryptUpdate(ctx, (unsigned char *)static_cast(p_enc_message), &len, static_cast(p_message), - p_message.lengthof()); - // 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, 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); - - return 0; -} - -int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_symmetric_key, const OCTETSTRING &p_nonce, - const OCTETSTRING &p_message, OCTETSTRING &p_enc_message) { - loggers::get_instance().log(">>> security_ecc::encrypt (2): %d", p_enc_algorithm); - - _encryption_algotithm = p_enc_algorithm; - _sym_key = p_symmetric_key; - _nonce = p_nonce; - - // Initialize the context and encryption operation - EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); - switch (_encryption_algotithm) { - case encryption_algotithm::aes_128_ccm: - ::EVP_EncryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); - // Allocate buffers size - _tag = int2oct(0, 16); - p_enc_message = int2oct(0, p_message.lengthof()); - break; - case encryption_algotithm::aes_256_ccm: - ::EVP_EncryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_128_gcm: - ::EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_256_gcm: - ::EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); - break; - } // End of 'switch' statement - loggers::get_instance().log_msg("security_ecc::encrypt: _sym_key: ", _sym_key); - 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); - // Set tag length - ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_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 - // Encrypt the data - int len = 0; - ::EVP_EncryptUpdate(ctx, (unsigned char *)static_cast(p_enc_message), &len, static_cast(p_message), - p_message.lengthof()); - // Finalize the encryption session - ::EVP_EncryptFinal_ex(ctx, (unsigned char *)static_cast(p_enc_message) + len, &len); - // Get the authentication tag - ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_GET_TAG, _tag.lengthof(), (unsigned char *)static_cast(_tag)); - loggers::get_instance().log_msg("security_ecc::encrypt: tag: ", _tag); - - ::EVP_CIPHER_CTX_free(ctx); - - return 0; -} - -int security_ecc::decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_key, const OCTETSTRING &p_nonce, const OCTETSTRING &p_tag, - const OCTETSTRING &p_enc_message, OCTETSTRING &p_message) { - loggers::get_instance().log(">>> security_ecc::decrypt: p_enc_algorithm=%d", p_enc_algorithm); - loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_key=", p_key); - loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_nonce", p_nonce); - loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_tag", p_tag); - loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_enc_message", p_enc_message); - - _encryption_algotithm = p_enc_algorithm; - _sym_key = p_key; - _nonce = p_nonce; - _tag = p_tag; - - // Initialize the context and decryption operation - EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); - switch (_encryption_algotithm) { - case encryption_algotithm::aes_128_ccm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_256_ccm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_128_gcm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_256_gcm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); - break; - } // End of 'switch' statement - // Set nonce length - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, _nonce.lengthof(), nullptr); - // Set expected tag value - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, _tag.lengthof(), (unsigned char *)static_cast(_tag)); - // Specify key and IV - EVP_DecryptInit_ex(ctx, nullptr, nullptr, static_cast(_sym_key), static_cast(_nonce)); - // Decrypt plaintext, verify tag: can only be called once - p_message = int2oct(0, p_enc_message.lengthof()); - int len = 0; - int result = EVP_DecryptUpdate(ctx, (unsigned char *)static_cast(p_message), &len, static_cast(p_enc_message), - p_enc_message.lengthof()); - loggers::get_instance().log("security_ecc::decrypt: len: %d", len); - loggers::get_instance().log("security_ecc::decrypt: result: %d", result); - ::EVP_CIPHER_CTX_free(ctx); - - return (result > 0) ? 0 : -1; -} - -int security_ecc::decrypt(const OCTETSTRING &p_tag, const OCTETSTRING &p_enc_message, OCTETSTRING &p_message) { - loggers::get_instance().log(">>> security_ecc::decrypt: %d", _encryption_algotithm); - - // Sanity checks - if ((_pri_key.lengthof() == 0) || (_secret_key.lengthof() == 0)) { - loggers::get_instance().warning("security_ecc::decrypt: Constrictor format #2 shall be used"); - return -1; - } - _tag = p_tag; - - // Initialize the context and decryption operation - EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); - switch (_encryption_algotithm) { - case encryption_algotithm::aes_128_ccm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_256_ccm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_128_gcm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); - break; - case encryption_algotithm::aes_256_gcm: - ::EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); - break; - } // End of 'switch' statement - // Set nonce length - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, _nonce.lengthof(), nullptr); - // Set expected tag value - EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, _tag.lengthof(), (unsigned char *)static_cast(_tag)); - // Specify key and IV - EVP_DecryptInit_ex(ctx, nullptr, nullptr, static_cast(_sym_key), static_cast(_nonce)); - // Decrypt plaintext, verify tag: can only be called once - p_message = int2oct(0, p_enc_message.lengthof()); - int len = 0; - int result = EVP_DecryptUpdate(ctx, (unsigned char *)static_cast(p_message), &len, static_cast(p_enc_message), - p_enc_message.lengthof()); - loggers::get_instance().log("security_ecc::decrypt: len: %d", len); - loggers::get_instance().log("security_ecc::decrypt: result: %d", result); - ::EVP_CIPHER_CTX_free(ctx); - - return (result > 0) ? 0 : -1; -} - -int security_ecc::sign(const OCTETSTRING &p_data, OCTETSTRING &p_r_sig, OCTETSTRING &p_s_sig) { - loggers::get_instance().log(">>> security_ecc::sign"); - loggers::get_instance().log_msg(">>> security_ecc::sign: p_data: ", p_data); - - // Sanity checks - if (_pri_key.lengthof() == 0) { // No private key - return -1; - } - if (p_data.lengthof() == 0) { - return -1; - } - - ECDSA_SIG *signature = ::ECDSA_do_sign(static_cast(p_data), p_data.lengthof(), _ec_key); - if (signature == nullptr) { - loggers::get_instance().warning("security_ecc::sign: Signature failed"); - return -1; - } - loggers::get_instance().log("security_ecc::sign: succeed"); - - if (::ECDSA_do_verify(static_cast(p_data), p_data.lengthof(), signature, _ec_key) != 1) { - loggers::get_instance().warning("security_ecc::sign: Signature not verified"); - return -1; - } - - const BIGNUM *r = nullptr; - const BIGNUM *s = nullptr; - ::ECDSA_SIG_get0(signature, &r, &s); - loggers::get_instance().log("security_ecc::sign: r size: %d", BN_num_bytes(r)); - p_r_sig = int2oct(0, BN_num_bytes(r)); - ::BN_bn2bin(r, (unsigned char *)static_cast(p_r_sig)); - loggers::get_instance().log_msg("security_ecc::sign: r=", p_r_sig); - loggers::get_instance().log("security_ecc::sign: s size: %d", BN_num_bytes(s)); - p_s_sig = int2oct(0, BN_num_bytes(s)); - ::BN_bn2bin(s, (unsigned char *)static_cast(p_s_sig)); - loggers::get_instance().log_msg("security_ecc::sign: s=", p_s_sig); - - ::ECDSA_SIG_free(signature); - - return 0; -} - -int security_ecc::sign_verif(const OCTETSTRING &p_data, const OCTETSTRING &p_signature) { - loggers::get_instance().log(">>> security_ecc::sign_verif"); - loggers::get_instance().log_msg(">>> security_ecc::sign_verify: p_data: ", p_data); - - // Sanity checks - if (p_data.lengthof() == 0) { - return -1; - } - - // Build the signature - BIGNUM *r = ::BN_bin2bn(static_cast(p_signature), p_signature.lengthof() / 2, nullptr); - loggers::get_instance().log_to_hexa("security_ecc::sign_verify: r=", static_cast(p_signature), p_signature.lengthof() / 2); - BIGNUM *s = ::BN_bin2bn(static_cast(p_signature) + p_signature.lengthof() / 2, p_signature.lengthof() / 2, nullptr); - loggers::get_instance().log_to_hexa("security_ecc::sign_verify: s=", static_cast(p_signature) + p_signature.lengthof() / 2, - p_signature.lengthof() / 2); - ECDSA_SIG *signature = ECDSA_SIG_new(); - ::ECDSA_SIG_set0(signature, r, s); - // Check the signature - int result = ::ECDSA_do_verify(static_cast(p_data), p_data.lengthof(), signature, _ec_key); - ::ECDSA_SIG_free(signature); - loggers::get_instance().log("security_ecc::sign_verif: %s", (result == 1) ? "succeed" : "failed"); - return (result == 1) ? 0 : -1; -} -const int security_ecc::init() { - loggers::get_instance().log(">>> security_ecc::init: %d", static_cast(_elliptic_curve)); - - ::OpenSSL_add_all_algorithms(); - ::ERR_load_crypto_strings(); - ::ERR_clear_error(); - - int result = -1; - switch (_elliptic_curve) { - case ec_elliptic_curves::nist_p_256: // Use the ANSI X9.62 Prime 256v1 curve - result = ::OBJ_txt2nid("prime256v1"); - break; - case ec_elliptic_curves::brainpool_p_256_r1: - result = ::OBJ_txt2nid("brainpoolP256r1"); - break; - case ec_elliptic_curves::brainpool_p_384_r1: - result = ::OBJ_txt2nid("brainpoolP384r1"); - break; - default: - loggers::get_instance().error("security_ecc::init: Unsupported EC elliptic_curve"); - } // End of 'switch' statement - if (result < 0) { - loggers::get_instance().warning("security_ecc::init: Unaible to set EC elliptic_curve"); - return -1; - } - loggers::get_instance().log("security_ecc::init: Nid=%d", result); - - _ec_key = ::EC_KEY_new_by_curve_name(result); // Set the elliptic curve - ::EC_KEY_set_asn1_flag(_ec_key, OPENSSL_EC_NAMED_CURVE); // Used to save and retrieve keys - _ec_group = ::EC_KEY_get0_group(_ec_key); // Get pointer to the EC_GROUP - _bn_ctx = ::BN_CTX_new(); - - return 0; -} // End of init - -int security_ecc::bin_to_ec_point(const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, - EC_POINT **p_ec_point) { // ec_key_public_key_bin_to_point - BIGNUM *pubk_bn; - - OCTETSTRING v = int2oct(4, 1); - v += p_public_key_x; - v += p_public_key_y; - - pubk_bn = ::BN_bin2bn(static_cast(v), v.lengthof(), nullptr); - *p_ec_point = ::EC_POINT_new(_ec_group); - ::EC_POINT_bn2point(_ec_group, pubk_bn, *p_ec_point, _bn_ctx); - ::BN_clear_free(pubk_bn); - - // BIO *bio_out = nullptr; /* stdout */ - // bio_out = BIO_new_fp(stdout, BIO_NOCLOSE); - // BIGNUM *x = BN_new(); - // BIGNUM *y = BN_new(); - - // if (EC_POINT_get_affine_coordinates_GFp(_ec_group, *p_ec_point, x, y, nullptr)) { - // BN_print_fp(stdout, x); - // putc('\n', stdout); - // BN_print_fp(stdout, y); - // putc('\n', stdout); - // } - // BN_free(x); BN_free(y); - - return 0; -} - -int security_ecc::public_key_to_bin(OCTETSTRING &p_bin_key) { // ec_key_public_key_to_bin - const EC_GROUP *ec_group = EC_KEY_get0_group(_ec_key); - const EC_POINT *pub = EC_KEY_get0_public_key(_ec_key); - BIGNUM *pub_bn = BN_new(); - - ::EC_POINT_point2bn(ec_group, pub, POINT_CONVERSION_UNCOMPRESSED, pub_bn, _bn_ctx); - p_bin_key = int2oct(0, BN_num_bytes(pub_bn)); - ::BN_bn2bin(pub_bn, (unsigned char *)static_cast(p_bin_key)); - - ::BN_clear_free(pub_bn); - - 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; -} +/*! + * \file security_ecc.cc + * \brief Source file for Elliptic Curve Cryptography. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include + +#include +#include + +#include "sha256.hh" + +#include "hmac.hh" +#include "security_ecc.hh" + +#include "loggers.hh" + +#if OPENSSL_VERSION_NUMBER >= 0x10101000L +#define EC_POINT_get_affine_coordinates_GFp EC_POINT_get_affine_coordinates +#define EC_POINT_get_affine_coordinates_GF2m EC_POINT_get_affine_coordinates +#define EC_POINT_set_affine_coordinates_GFp EC_POINT_set_affine_coordinates +#define EC_POINT_set_affine_coordinates_GF2m EC_POINT_set_affine_coordinates +#define EC_POINT_set_compressed_coordinates_GFp EC_POINT_set_compressed_coordinates +#define EC_POINT_set_compressed_coordinates_GF2m EC_POINT_set_compressed_coordinates +#endif + +security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve) + : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), + _pri_key(), _pub_key_x(), _pub_key_y(), _pub_key_compressed(), _pub_key_compressed_mode{ecc_compressed_mode::compressed_y_0}, _secret_key(), _enc_key_x(), + _enc_key_y(), _sym_key(), _nonce(), _tag() { + loggers::get_instance().log(">>> security_ecc::security_ecc: %d", static_cast(p_elliptic_curve)); + + const int result = init(); + if (result == -1) { + loggers::get_instance().error("security_ecc::security_ecc: Unsupported elliptic_curve %d", _elliptic_curve); + } +} // End of constructor + +security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_private_key) + : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), + _pri_key(p_private_key), _pub_key_x(), _pub_key_y(), _pub_key_compressed(), _pub_key_compressed_mode{ecc_compressed_mode::compressed_y_0}, _secret_key(), + _enc_key_x(), _enc_key_y(), _sym_key(), _nonce(), _tag() { + loggers::get_instance().log(">>> security_ecc::security_ecc (1): %d", static_cast(p_elliptic_curve)); + + // Sanity checks + if ((_elliptic_curve == ec_elliptic_curves::nist_p_256) || (_elliptic_curve == ec_elliptic_curves::brainpool_p_256_r1)) { + if (p_private_key.lengthof() != 32) { + loggers::get_instance().error("security_ecc::security_ecc (1): Invalid public keys size"); + } + } else if (_elliptic_curve == ec_elliptic_curves::brainpool_p_384_r1) { + if ((p_private_key.lengthof() != 48)) { + loggers::get_instance().error("security_ecc::security_ecc (1): Invalid public keys size"); + } + } + + int result = init(); + if (result == -1) { + loggers::get_instance().error("security_ecc::security_ecc (1): Unsupported elliptic_curve %d", _elliptic_curve); + } + ::EC_KEY_set_conv_form(_ec_key, POINT_CONVERSION_UNCOMPRESSED); + + // Build private key + BIGNUM *p = ::BN_new(); + ::BN_bin2bn(static_cast(_pri_key), _pri_key.lengthof(), p); + // Build public keys + EC_POINT *ec_point = ::EC_POINT_new(_ec_group); + ::EC_POINT_mul(_ec_group, ec_point, p, nullptr, nullptr, _bn_ctx); + // Set private key + ::EC_KEY_set_private_key(_ec_key, p); + if (::EC_KEY_check_key(_ec_key) != 0) { + ::BN_clear_free(p); + loggers::get_instance().error("security_ecc::security_ecc (1): Invalid private key"); + } + ::BN_clear_free(p); + p = nullptr; + // Private key is correct, set public keys + ::EC_KEY_set_public_key(_ec_key, ec_point); + + BIGNUM *xy = ::BN_new(); + ::EC_POINT_point2bn(_ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, xy, _bn_ctx); + if (BN_num_bytes(xy) == 0) { + ::BN_clear_free(xy); + loggers::get_instance().error("security_ecc::security_ecc (1): Failed to generate xy coordinates, check algorithms"); + } + loggers::get_instance().log("security_ecc::security_ecc (1): xy length: %d", BN_num_bytes(xy)); + OCTETSTRING v = int2oct(0, BN_num_bytes(xy)); + ::BN_bn2bin(xy, (unsigned char *)static_cast(v)); + if ((v.lengthof() % 2) != 0) { + // Remove first byte + loggers::get_instance().log_msg("security_ecc::security_ecc (1): Complete xy=", v); + v = OCTETSTRING(v.lengthof() - 1, 1 + static_cast(v)); + } + ::BN_clear_free(xy); + xy = nullptr; + + loggers::get_instance().log_msg("security_ecc::security_ecc (1): xy=", v); + const int l = v.lengthof() / 2; + _pub_key_x = OCTETSTRING(l, static_cast(v)); + _pub_key_y = OCTETSTRING(l, l + static_cast(v)); + + // Compressed + int len = ::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, nullptr, 0, _bn_ctx); + if (len == 0) { + loggers::get_instance().warning("security_ecc::security_ecc (1): Failed to generate x_coordinate compressed key"); + _pub_key_compressed = OCTETSTRING(0, nullptr); + } else { + _pub_key_compressed = int2oct(0, len); + if (::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, (unsigned char *)static_cast(_pub_key_compressed), len, + _bn_ctx) == 0) { + loggers::get_instance().warning("security_ecc::security_ecc (1): Failed to generate x_coordinate compressed key"); + _pub_key_compressed = OCTETSTRING(0, nullptr); + } else { // Remove first byte + loggers::get_instance().log_msg("security_ecc::security_ecc (1): Complete _pub_key_compressed=", _pub_key_compressed); + _pub_key_compressed_mode = ((v[0].get_octet() & 0x01) == 0x00) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1; + _pub_key_compressed = OCTETSTRING(_pub_key_compressed.lengthof() - 1, 1 + static_cast(_pub_key_compressed)); + } + } + ::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); + loggers::get_instance().log("security_ecc::security_ecc (1): _pub_key_compressed_mode=%d", _pub_key_compressed_mode); +} // End of constructor + +security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y) + : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), + _pri_key(), _pub_key_x(p_public_key_x), _pub_key_y(p_public_key_y), _pub_key_compressed(), _pub_key_compressed_mode{ecc_compressed_mode::compressed_y_0}, + _secret_key(), _enc_key_x(), _enc_key_y(), _sym_key(), _nonce(), _tag() { + loggers::get_instance().log(">>> security_ecc::security_ecc (2): %d", static_cast(p_elliptic_curve)); + + // Sanity checks + if ((_elliptic_curve == ec_elliptic_curves::nist_p_256) || (_elliptic_curve == ec_elliptic_curves::brainpool_p_256_r1)) { + if ((p_public_key_x.lengthof() != 32) || (p_public_key_y.lengthof() != 32)) { + loggers::get_instance().error("security_ecc::security_ecc (2): Invalid public keys size"); + } + } else if (_elliptic_curve == ec_elliptic_curves::brainpool_p_384_r1) { + if ((p_public_key_x.lengthof() != 48) || (p_public_key_y.lengthof() != 48)) { + loggers::get_instance().error("security_ecc::security_ecc (2): Invalid public keys size"); + } + } + + int result = init(); + if (result == -1) { + loggers::get_instance().error("security_ecc::security_ecc (2): Unsupported elliptic_curve %d", _elliptic_curve); + } + ::EC_KEY_set_conv_form(_ec_key, POINT_CONVERSION_UNCOMPRESSED); + + // Set public key + BIGNUM *x = ::BN_new(); + ::BN_bin2bn(static_cast(_pub_key_x), _pub_key_x.lengthof(), x); + BIGNUM *y = ::BN_new(); + ::BN_bin2bn(static_cast(_pub_key_y), _pub_key_y.lengthof(), y); + EC_POINT *ec_point = ::EC_POINT_new(_ec_group); + result = 0; + switch (_elliptic_curve) { + case ec_elliptic_curves::nist_p_256: // Use primary + // No break; + case ec_elliptic_curves::brainpool_p_256_r1: + // No break; + case ec_elliptic_curves::brainpool_p_384_r1: + result = ::EC_POINT_set_affine_coordinates_GFp(_ec_group, ec_point, x, y, _bn_ctx); // Use primary elliptic curve + break; + default: // Use Binary + result = 0; // FIXME Does not compile on Windows ::EC_POINT_set_affine_coordinates_GF2m(_ec_group, ec_point, x, y, _bn_ctx); + } // End of 'switch' statement + if (result == 0) { + ::BN_clear_free(x); + ::BN_clear_free(y); + loggers::get_instance().error("security_ecc::security_ecc (2): Failed to get coordinates"); + } + ::BN_clear_free(x); + x = nullptr; + ::BN_clear_free(y); + y = nullptr; + + ::EC_KEY_set_public_key(_ec_key, ec_point); + + // Compressed + int len = ::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, nullptr, 0, _bn_ctx); + if (len == 0) { + loggers::get_instance().warning("security_ecc::security_ecc (2): Failed to generate x_coordinate compressed key"); + } + _pub_key_compressed = int2oct(0, len); + if (::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, (unsigned char *)static_cast(_pub_key_compressed), len, + _bn_ctx) == 0) { + loggers::get_instance().warning("security_ecc::security_ecc (2): Failed to generate x_coordinate compressed key"); + _pub_key_compressed = OCTETSTRING(0, nullptr); + } else { // Remove first byte + loggers::get_instance().log_msg("security_ecc::security_ecc (2): Complete _pub_key_compressed=", _pub_key_compressed); + _pub_key_compressed = OCTETSTRING(_pub_key_compressed.lengthof() - 1, 1 + static_cast(_pub_key_compressed)); + } + ::EC_POINT_free(ec_point); + loggers::get_instance().log_msg("security_ecc::security_ecc (2): _pub_key_x=", _pub_key_x); + loggers::get_instance().log_msg("security_ecc::security_ecc (2): _pub_key_y=", _pub_key_y); + loggers::get_instance().log_msg("security_ecc::security_ecc (2): _pub_key_compressed=", _pub_key_compressed); + loggers::get_instance().log("security_ecc::security_ecc (2): _pub_key_compressed_mode=%d", _pub_key_compressed_mode); +} // End of constructor + +security_ecc::security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_compressed, const ecc_compressed_mode p_compressed_mode) + : _elliptic_curve(p_elliptic_curve), _encryption_algotithm(encryption_algotithm::aes_128_ccm), _ec_key(nullptr), _ec_group(nullptr), _bn_ctx(nullptr), + _pri_key(), _pub_key_x(), _pub_key_y(), _pub_key_compressed(p_public_key_compressed), _pub_key_compressed_mode{p_compressed_mode}, _secret_key(), + _enc_key_x(), _enc_key_y(), _sym_key(), _nonce(), _tag() { + loggers::get_instance().log(">>> security_ecc::security_ecc (3): %d", static_cast(p_elliptic_curve)); + + // Sanity checks + if ((_elliptic_curve == ec_elliptic_curves::nist_p_256) || (_elliptic_curve == ec_elliptic_curves::brainpool_p_256_r1)) { + if (p_public_key_compressed.lengthof() != 32) { + loggers::get_instance().error("security_ecc::security_ecc (3): Invalid public keys size"); + } + } else if (_elliptic_curve == ec_elliptic_curves::brainpool_p_384_r1) { + if (p_public_key_compressed.lengthof() != 48) { + loggers::get_instance().error("security_ecc::security_ecc (3): Invalid public keys size"); + } + } + + int result = init(); + if (result == -1) { + loggers::get_instance().error("security_ecc::security_ecc (3): Unsupported elliptic_curve %d", _elliptic_curve); + } + ::EC_KEY_set_conv_form(_ec_key, POINT_CONVERSION_UNCOMPRESSED); + + // Set public key + BIGNUM *compressed_key = ::BN_new(); + ::BN_bin2bn(static_cast(_pub_key_compressed), _pub_key_compressed.lengthof(), compressed_key); + EC_POINT *ec_point = ::EC_POINT_new(_ec_group); + result = 0; + switch (_elliptic_curve) { + case ec_elliptic_curves::nist_p_256: // Use primary + // No break; + case ec_elliptic_curves::brainpool_p_256_r1: + // No break; + case ec_elliptic_curves::brainpool_p_384_r1: + result = ::EC_POINT_set_compressed_coordinates_GFp( + _ec_group, ec_point, compressed_key, (p_compressed_mode == ecc_compressed_mode::compressed_y_1) ? 1 : 0, _bn_ctx); // Use primary elliptic curve + break; + default: // Use Binary + result = 0; // FIXME Does not compile on Windows ::EC_POINT_set_compressed_coordinates_GF2m(_ec_group, ec_point, compressed_key, (p_compressed_mode == + // ecc_compressed_mode::compressed_y_1) ? 1 : 0, _bn_ctx); + } // End of 'switch' statement + BN_clear_free(compressed_key); + compressed_key = nullptr; + + if (result == 0) { + loggers::get_instance().error("security_ecc::security_ecc (3): Failed to get coordinates"); + } else if (::EC_POINT_is_on_curve(_ec_group, ec_point, _bn_ctx) == 0) { + loggers::get_instance().error("security_ecc::security_ecc (3): Point Y0 is not on the curve"); + } + + // Set public keys + BIGNUM *xy = ::BN_new(); + ::EC_POINT_point2bn(_ec_group, ec_point, POINT_CONVERSION_UNCOMPRESSED, xy, _bn_ctx); + if (BN_num_bytes(xy) == 0) { + ::BN_clear_free(xy); + loggers::get_instance().error("security_ecc::security_ecc (3): Failed to generate xy coordinates, check algorithms"); + } + loggers::get_instance().log("security_ecc::security_ecc (3): xy length: %d", BN_num_bytes(xy)); + ::EC_KEY_set_public_key(_ec_key, ec_point); + // Generate X, Y coordinates + OCTETSTRING v = int2oct(0, BN_num_bytes(xy)); + ::BN_bn2bin(xy, (unsigned char *)static_cast(v)); + ::BN_clear_free(xy); + xy = nullptr; + if ((v.lengthof() % 2) != 0) { // TODO Check alse xy[0] == 0x04 + // Remove first byte + loggers::get_instance().log_msg("security_ecc::security_ecc (3): Complete xy=", v); + v = OCTETSTRING(v.lengthof() - 1, 1 + static_cast(v)); + } + loggers::get_instance().log_msg("security_ecc::security_ecc (3): xy=", v); + const int l = v.lengthof() / 2; + _pub_key_x = OCTETSTRING(l, static_cast(v)); + _pub_key_y = OCTETSTRING(l, l + static_cast(v)); + ::EC_POINT_free(ec_point); + + loggers::get_instance().log_msg("security_ecc::security_ecc (3): _pub_key_x=", _pub_key_x); + loggers::get_instance().log_msg("security_ecc::security_ecc (3): _pub_key_y=", _pub_key_y); + loggers::get_instance().log_msg("security_ecc::security_ecc (3): _pub_key_compressed=", _pub_key_compressed); + loggers::get_instance().log("security_ecc::security_ecc (3): _pub_key_compressed_mode=%d", _pub_key_compressed_mode); +} // End of constructor + +security_ecc::~security_ecc() { + loggers::get_instance().log(">>> security_ecc::~security_ecc"); + + if (_ec_key != nullptr) { + ::EC_KEY_free(_ec_key); + } + if (_bn_ctx != nullptr) { + ::BN_CTX_free(_bn_ctx); + } + + loggers::get_instance().log("<<< security_ecc::~security_ecc"); +} // End of Destructor + +int security_ecc::generate() { + loggers::get_instance().log(">>> security_ecc::generate"); + + // Sanity check + if (!::EC_KEY_generate_key(_ec_key)) { // Generate the private and public keys + loggers::get_instance().error("security_ecc::generate: Failed to generate private/public keys"); + return -1; + } + + BIGNUM * x = ::BN_new(); + BIGNUM * y = ::BN_new(); + const EC_POINT *ec_point = EC_KEY_get0_public_key(_ec_key); + int result = 0; + int size = 0; + switch (_elliptic_curve) { + case ec_elliptic_curves::nist_p_256: // Use primary + // No break; + case ec_elliptic_curves::brainpool_p_256_r1: + size = 32; + result = ::EC_POINT_get_affine_coordinates_GFp(_ec_group, ec_point, x, y, _bn_ctx); // Use primer on elliptic curve + break; + case ec_elliptic_curves::brainpool_p_384_r1: + size = 48; + result = ::EC_POINT_get_affine_coordinates_GFp(_ec_group, ec_point, x, y, _bn_ctx); // Use primer on elliptic curve + break; + default: // Use binary + result = 0; // FIXME Does not compile on Windows ::EC_POINT_get_affine_coordinates_GF2m(_ec_group, ec_point, x, y, _bn_ctx); + } // End of 'switch' statement + if (result == 0) { + loggers::get_instance().error("security_ecc::generate: Failed to get coordinates"); + } + const BIGNUM *p = ::EC_KEY_get0_private_key(_ec_key); + + _pri_key = int2oct(0, size); + ::BN_bn2bin(p, (unsigned char *)static_cast(_pri_key)); + _pub_key_x = int2oct(0, size); + ::BN_bn2bin(x, (unsigned char *)static_cast(_pub_key_x)); + _pub_key_y = int2oct(0, size); + ::BN_bn2bin(y, (unsigned char *)static_cast(_pub_key_y)); + ::BN_clear_free(x); + x = nullptr; + ::BN_clear_free(y); + y = nullptr; + + // Compressed + int len = ::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, nullptr, 0, _bn_ctx); + if (len == 0) { + loggers::get_instance().warning("security_ecc::generate: Failed to generate x_coordinate compressed key"); + } + _pub_key_compressed = int2oct(0, len); + if (::EC_POINT_point2oct(_ec_group, ec_point, POINT_CONVERSION_COMPRESSED, (unsigned char *)static_cast(_pub_key_compressed), len, + _bn_ctx) == 0) { + loggers::get_instance().warning("security_ecc::generate: Failed to generate x_coordinate compressed key"); + _pub_key_compressed = OCTETSTRING(0, nullptr); + } else { // Remove first byte + loggers::get_instance().log_msg("security_ecc::generate: Complete _pub_key_compressed=", _pub_key_compressed); + _pub_key_compressed_mode = + ((_pub_key_compressed[0].get_octet() & 0x01) == 0x00) ? ecc_compressed_mode::compressed_y_0 : ecc_compressed_mode::compressed_y_1; + _pub_key_compressed = OCTETSTRING(_pub_key_compressed.lengthof() - 1, 1 + static_cast(_pub_key_compressed)); + } + loggers::get_instance().log_msg("security_ecc::generate: _pri_key=", _pri_key); + loggers::get_instance().log_msg("security_ecc::generate: _pub_key_x=", _pub_key_x); + loggers::get_instance().log_msg("security_ecc::generate: _pub_key_y=", _pub_key_y); + loggers::get_instance().log_msg("security_ecc::generate: _pub_key_compressed=", _pub_key_compressed); + loggers::get_instance().log("security_ecc::generate: _pub_key_compressed_mode=%d", _pub_key_compressed_mode); + + 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, 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) { + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Key shall be generated"); + return -1; + } + if ((_pub_key_x.lengthof() == 0) || (_pub_key_y.lengthof() == 0)) { + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Keys shall be generated"); + return -1; + } + _encryption_algotithm = p_enc_algorithm; + + // 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; + unsigned int tag_length; + switch (_encryption_algotithm) { + case encryption_algotithm::aes_128_ccm: + // No break; + case encryption_algotithm::aes_128_gcm: + nonce_length = 12; + sym_key_length = 16; + tag_length = 16; + break; + default: + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Unsupported encryption algorithm"); + return -1; + } // End of 'switch' statement + 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_enc = 16; + k_mac = 32; + break; + case ec_elliptic_curves::brainpool_p_384_r1: + 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"); + return -1; + } // End of 'switch' statement + + // 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 (Key Agreement) + int result = ::ECDH_compute_key((unsigned char *)static_cast(_secret_key), _secret_key.lengthof(), + ec_point, // From recipient's public key + _ec_key, // From ephemeral's private key + nullptr); + if (result != _secret_key.lengthof()) { + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (1): Failed to generate shared secret key"); + ::EC_POINT_free(ec_point); + return -1; + } + ::EC_POINT_free(ec_point); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (1): _secret_key: ", _secret_key); + + // Derive the shared secret key + 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 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, nonce_length * 8, -1, 0); + _nonce = int2oct(0, nonce_length); + ::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_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 ((_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; + _tag = p_authentication_vector; + + // 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; + unsigned int tag_length; + switch (_encryption_algotithm) { + case encryption_algotithm::aes_128_ccm: + // No break; + case encryption_algotithm::aes_128_gcm: + nonce_length = 12; + sym_key_length = 16; + tag_length = 16; + break; + default: + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Unsupported encryption algorithm"); + return -1; + } // End of 'switch' statement + 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_enc = 16; + k_mac = 32; + break; + case ec_elliptic_curves::brainpool_p_384_r1: + break; + default: + loggers::get_instance().warning("security_ecc::generate_and_derive_ephemeral_key (2): Unsupported encryption algorithm"); + return -1; + } // 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(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, // From recipient's private key + _ec_key, // From sender's public key + nullptr); + if (result != _secret_key.lengthof()) { + 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; + } + ::EC_POINT_free(ec_point); + loggers::get_instance().log_msg("security_ecc::generate_and_derive_ephemeral_key (2): _secret_key: ", _secret_key); + + // Derive the shared secret key + 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 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::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)) { + loggers::get_instance().warning("security_ecc::encrypt: Constructor format #1 shall be used"); + return -1; + } + _encryption_algotithm = p_enc_algorithm; + + // 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); + // 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_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 + ::RAND_bytes((unsigned char *)static_cast(_sym_key), _sym_key.lengthof()); + loggers::get_instance().log_msg("security_ecc::encrypt: _sym_key: ", _sym_key); + // Generate _nonce + ::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, ctr_set_iv_len, _nonce.lengthof(), nullptr); + // Set tag length + ::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 + // Encrypt the data + int len = 0; + ::EVP_EncryptUpdate(ctx, (unsigned char *)static_cast(p_enc_message), &len, static_cast(p_message), + p_message.lengthof()); + // 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, 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); + + return 0; +} + +int security_ecc::encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_symmetric_key, const OCTETSTRING &p_nonce, + const OCTETSTRING &p_message, OCTETSTRING &p_enc_message) { + loggers::get_instance().log(">>> security_ecc::encrypt (2): %d", p_enc_algorithm); + + _encryption_algotithm = p_enc_algorithm; + _sym_key = p_symmetric_key; + _nonce = p_nonce; + + // Initialize the context and encryption operation + EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); + switch (_encryption_algotithm) { + case encryption_algotithm::aes_128_ccm: + ::EVP_EncryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); + // Allocate buffers size + _tag = int2oct(0, 16); + p_enc_message = int2oct(0, p_message.lengthof()); + break; + case encryption_algotithm::aes_256_ccm: + ::EVP_EncryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_128_gcm: + ::EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_256_gcm: + ::EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); + break; + } // End of 'switch' statement + loggers::get_instance().log_msg("security_ecc::encrypt: _sym_key: ", _sym_key); + 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); + // Set tag length + ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_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 + // Encrypt the data + int len = 0; + ::EVP_EncryptUpdate(ctx, (unsigned char *)static_cast(p_enc_message), &len, static_cast(p_message), + p_message.lengthof()); + // Finalize the encryption session + ::EVP_EncryptFinal_ex(ctx, (unsigned char *)static_cast(p_enc_message) + len, &len); + // Get the authentication tag + ::EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_GET_TAG, _tag.lengthof(), (unsigned char *)static_cast(_tag)); + loggers::get_instance().log_msg("security_ecc::encrypt: tag: ", _tag); + + ::EVP_CIPHER_CTX_free(ctx); + + return 0; +} + +int security_ecc::decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_key, const OCTETSTRING &p_nonce, const OCTETSTRING &p_tag, + const OCTETSTRING &p_enc_message, OCTETSTRING &p_message) { + loggers::get_instance().log(">>> security_ecc::decrypt: p_enc_algorithm=%d", p_enc_algorithm); + loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_key=", p_key); + loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_nonce", p_nonce); + loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_tag", p_tag); + loggers::get_instance().log_msg(">>> security_ecc::decrypt: p_enc_message", p_enc_message); + + _encryption_algotithm = p_enc_algorithm; + _sym_key = p_key; + _nonce = p_nonce; + _tag = p_tag; + + // Initialize the context and decryption operation + EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); + switch (_encryption_algotithm) { + case encryption_algotithm::aes_128_ccm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_256_ccm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_128_gcm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_256_gcm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); + break; + } // End of 'switch' statement + // Set nonce length + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, _nonce.lengthof(), nullptr); + // Set expected tag value + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, _tag.lengthof(), (unsigned char *)static_cast(_tag)); + // Specify key and IV + EVP_DecryptInit_ex(ctx, nullptr, nullptr, static_cast(_sym_key), static_cast(_nonce)); + // Decrypt plaintext, verify tag: can only be called once + p_message = int2oct(0, p_enc_message.lengthof()); + int len = 0; + int result = EVP_DecryptUpdate(ctx, (unsigned char *)static_cast(p_message), &len, static_cast(p_enc_message), + p_enc_message.lengthof()); + loggers::get_instance().log("security_ecc::decrypt: len: %d", len); + loggers::get_instance().log("security_ecc::decrypt: result: %d", result); + ::EVP_CIPHER_CTX_free(ctx); + + return (result > 0) ? 0 : -1; +} + +int security_ecc::decrypt(const OCTETSTRING &p_tag, const OCTETSTRING &p_enc_message, OCTETSTRING &p_message) { + loggers::get_instance().log(">>> security_ecc::decrypt: %d", _encryption_algotithm); + + // Sanity checks + if ((_pri_key.lengthof() == 0) || (_secret_key.lengthof() == 0)) { + loggers::get_instance().warning("security_ecc::decrypt: Constrictor format #2 shall be used"); + return -1; + } + _tag = p_tag; + + // Initialize the context and decryption operation + EVP_CIPHER_CTX *ctx = ::EVP_CIPHER_CTX_new(); + switch (_encryption_algotithm) { + case encryption_algotithm::aes_128_ccm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_128_ccm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_256_ccm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_256_ccm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_128_gcm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), nullptr, nullptr, nullptr); + break; + case encryption_algotithm::aes_256_gcm: + ::EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), nullptr, nullptr, nullptr); + break; + } // End of 'switch' statement + // Set nonce length + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_IVLEN, _nonce.lengthof(), nullptr); + // Set expected tag value + EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_CCM_SET_TAG, _tag.lengthof(), (unsigned char *)static_cast(_tag)); + // Specify key and IV + EVP_DecryptInit_ex(ctx, nullptr, nullptr, static_cast(_sym_key), static_cast(_nonce)); + // Decrypt plaintext, verify tag: can only be called once + p_message = int2oct(0, p_enc_message.lengthof()); + int len = 0; + int result = EVP_DecryptUpdate(ctx, (unsigned char *)static_cast(p_message), &len, static_cast(p_enc_message), + p_enc_message.lengthof()); + loggers::get_instance().log("security_ecc::decrypt: len: %d", len); + loggers::get_instance().log("security_ecc::decrypt: result: %d", result); + ::EVP_CIPHER_CTX_free(ctx); + + return (result > 0) ? 0 : -1; +} + +int security_ecc::sign(const OCTETSTRING &p_data, OCTETSTRING &p_r_sig, OCTETSTRING &p_s_sig) { + loggers::get_instance().log(">>> security_ecc::sign"); + loggers::get_instance().log_msg(">>> security_ecc::sign: p_data: ", p_data); + + // Sanity checks + if (_pri_key.lengthof() == 0) { // No private key + return -1; + } + if (p_data.lengthof() == 0) { + return -1; + } + + ECDSA_SIG *signature = ::ECDSA_do_sign(static_cast(p_data), p_data.lengthof(), _ec_key); + if (signature == nullptr) { + loggers::get_instance().warning("security_ecc::sign: Signature failed"); + return -1; + } + loggers::get_instance().log("security_ecc::sign: succeed"); + + if (::ECDSA_do_verify(static_cast(p_data), p_data.lengthof(), signature, _ec_key) != 1) { + loggers::get_instance().warning("security_ecc::sign: Signature not verified"); + return -1; + } + + const BIGNUM *r = nullptr; + const BIGNUM *s = nullptr; + ::ECDSA_SIG_get0(signature, &r, &s); + loggers::get_instance().log("security_ecc::sign: r size: %d", BN_num_bytes(r)); + p_r_sig = int2oct(0, BN_num_bytes(r)); + ::BN_bn2bin(r, (unsigned char *)static_cast(p_r_sig)); + loggers::get_instance().log_msg("security_ecc::sign: r=", p_r_sig); + loggers::get_instance().log("security_ecc::sign: s size: %d", BN_num_bytes(s)); + p_s_sig = int2oct(0, BN_num_bytes(s)); + ::BN_bn2bin(s, (unsigned char *)static_cast(p_s_sig)); + loggers::get_instance().log_msg("security_ecc::sign: s=", p_s_sig); + + ::ECDSA_SIG_free(signature); + + return 0; +} + +int security_ecc::sign_verif(const OCTETSTRING &p_data, const OCTETSTRING &p_signature) { + loggers::get_instance().log(">>> security_ecc::sign_verif"); + loggers::get_instance().log_msg(">>> security_ecc::sign_verify: p_data: ", p_data); + + // Sanity checks + if (p_data.lengthof() == 0) { + return -1; + } + + // Build the signature + BIGNUM *r = ::BN_bin2bn(static_cast(p_signature), p_signature.lengthof() / 2, nullptr); + loggers::get_instance().log_to_hexa("security_ecc::sign_verify: r=", static_cast(p_signature), p_signature.lengthof() / 2); + BIGNUM *s = ::BN_bin2bn(static_cast(p_signature) + p_signature.lengthof() / 2, p_signature.lengthof() / 2, nullptr); + loggers::get_instance().log_to_hexa("security_ecc::sign_verify: s=", static_cast(p_signature) + p_signature.lengthof() / 2, + p_signature.lengthof() / 2); + ECDSA_SIG *signature = ECDSA_SIG_new(); + ::ECDSA_SIG_set0(signature, r, s); + // Check the signature + int result = ::ECDSA_do_verify(static_cast(p_data), p_data.lengthof(), signature, _ec_key); + ::ECDSA_SIG_free(signature); + loggers::get_instance().log("security_ecc::sign_verif: %s", (result == 1) ? "succeed" : "failed"); + return (result == 1) ? 0 : -1; +} +const int security_ecc::init() { + loggers::get_instance().log(">>> security_ecc::init: %d", static_cast(_elliptic_curve)); + + ::OpenSSL_add_all_algorithms(); + ::ERR_load_crypto_strings(); + ::ERR_clear_error(); + + int result = -1; + switch (_elliptic_curve) { + case ec_elliptic_curves::nist_p_256: // Use the ANSI X9.62 Prime 256v1 curve + result = ::OBJ_txt2nid("prime256v1"); + break; + case ec_elliptic_curves::brainpool_p_256_r1: + result = ::OBJ_txt2nid("brainpoolP256r1"); + break; + case ec_elliptic_curves::brainpool_p_384_r1: + result = ::OBJ_txt2nid("brainpoolP384r1"); + break; + default: + loggers::get_instance().error("security_ecc::init: Unsupported EC elliptic_curve"); + } // End of 'switch' statement + if (result < 0) { + loggers::get_instance().warning("security_ecc::init: Unaible to set EC elliptic_curve"); + return -1; + } + loggers::get_instance().log("security_ecc::init: Nid=%d", result); + + _ec_key = ::EC_KEY_new_by_curve_name(result); // Set the elliptic curve + ::EC_KEY_set_asn1_flag(_ec_key, OPENSSL_EC_NAMED_CURVE); // Used to save and retrieve keys + _ec_group = ::EC_KEY_get0_group(_ec_key); // Get pointer to the EC_GROUP + _bn_ctx = ::BN_CTX_new(); + + return 0; +} // End of init + +int security_ecc::bin_to_ec_point(const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, + EC_POINT **p_ec_point) { // ec_key_public_key_bin_to_point + BIGNUM *pubk_bn; + + OCTETSTRING v = int2oct(4, 1); + v += p_public_key_x; + v += p_public_key_y; + + pubk_bn = ::BN_bin2bn(static_cast(v), v.lengthof(), nullptr); + *p_ec_point = ::EC_POINT_new(_ec_group); + ::EC_POINT_bn2point(_ec_group, pubk_bn, *p_ec_point, _bn_ctx); + ::BN_clear_free(pubk_bn); + + // BIO *bio_out = nullptr; /* stdout */ + // bio_out = BIO_new_fp(stdout, BIO_NOCLOSE); + // BIGNUM *x = BN_new(); + // BIGNUM *y = BN_new(); + + // if (EC_POINT_get_affine_coordinates_GFp(_ec_group, *p_ec_point, x, y, nullptr)) { + // BN_print_fp(stdout, x); + // putc('\n', stdout); + // BN_print_fp(stdout, y); + // putc('\n', stdout); + // } + // BN_free(x); BN_free(y); + + return 0; +} + +int security_ecc::public_key_to_bin(OCTETSTRING &p_bin_key) { // ec_key_public_key_to_bin + const EC_GROUP *ec_group = EC_KEY_get0_group(_ec_key); + const EC_POINT *pub = EC_KEY_get0_public_key(_ec_key); + BIGNUM *pub_bn = BN_new(); + + ::EC_POINT_point2bn(ec_group, pub, POINT_CONVERSION_UNCOMPRESSED, pub_bn, _bn_ctx); + p_bin_key = int2oct(0, BN_num_bytes(pub_bn)); + ::BN_bn2bin(pub_bn, (unsigned char *)static_cast(p_bin_key)); + + ::BN_clear_free(pub_bn); + + 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 7dda068afe0df03f5b28c8713d43bde2aad72a74..a8abebe583428adb697c654e32ac4c5c9c8231e0 100644 --- a/ccsrc/Protocols/Security/security_ecc.hh +++ b/ccsrc/Protocols/Security/security_ecc.hh @@ -1,241 +1,241 @@ -/*! - * \file security_ecc.hh - * \brief Header file for Elliptic Curve Cryptography. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -class OCTETSTRING; //! TITAN forward declaration - -/*! - * \enum Supported Elliptic curves - */ -enum class ec_elliptic_curves : unsigned char { // TODO Renamed into ecc_elliptic_curves - nist_p_256, /*!< NIST P-256, P-256, primve256v1 */ - brainpool_p_256_r1, /*!< Brainpool P256r1 */ - brainpool_p_384_r1 /*!< Brainpool P384r1 */ -}; // End of class ecc_elliptic_curves - -/*! - * \enum Public key coordinates compression mode - */ -enum class ecc_compressed_mode : unsigned char { - compressed_y_0, /*!< The last significant bit of Y-coodinate ended with 0 */ - compressed_y_1 /*!< The last significant bit of Y-coodinate ended with 1 */ -}; // End of class ecc_compressed_mode - -/*! - * \enum Supported encryption algorithem - */ -enum class encryption_algotithm : unsigned char { // TODO Renamed into ecc_encryption_algotithm - aes_128_ccm, - aes_256_ccm, - aes_128_gcm, - aes_256_gcm -}; // End of class ecc_encryption_algotithm - -/*! - * \class security_ecc - * \brief This class implements the generation of a key pair private/public - */ -class security_ecc { - ec_elliptic_curves _elliptic_curve; /*!< Selected elleptic curve */ - encryption_algotithm _encryption_algotithm; /*!< Selected encryption algotithm */ - EC_KEY * _ec_key; /*!< EC_KEY reference */ - const EC_GROUP * _ec_group; /*!< EC_GROUP reference */ - BN_CTX * _bn_ctx; /*!< Pre-alocated memory used to increase OpenSSL processing */ - OCTETSTRING _pri_key; /*!< Private key storage */ - OCTETSTRING _pub_key_x; /*!< Public key X-coordinate storage */ - OCTETSTRING _pub_key_y; /*!< Public key Y-coordinate storage */ - OCTETSTRING _pub_key_compressed; /*!< Public key compressed */ - ecc_compressed_mode _pub_key_compressed_mode; /*!< Public key coordinates compression mode */ - OCTETSTRING _secret_key; /*!< Shared secret key generated by ECIES encryption method */ - OCTETSTRING _enc_key_x; /*!< Ephemeral public key X-coordinate storage */ - OCTETSTRING _enc_key_y; /*!< Ephemeral public key Y-coordinate storage */ - OCTETSTRING _sym_key; /*!< AES symmetric encryption key generated by encryption method */ - OCTETSTRING _enc_sym_key; /*!< Encrypted AES symmetric encryption key generated by encryption method */ - OCTETSTRING _nonce; /*!< Initial Vector generated by encryption method */ - OCTETSTRING _tag; /*!< Tag vector generated by encryption method */ - -public: //! \publicsection - /*! - * \brief Default constructor - * \param[in] p_elliptic_curve The ECDSA curve family to be used - * \remark Call the method security_ecc::generate() to initialise the private/public key pair - */ - security_ecc(const ec_elliptic_curves p_elliptic_curve); - /*! - * \brief Constructor based on the private key only - * \param[in] p_elliptic_curve The ECDSA curve family to be used - * \param[in] p_private_key The private key - * \remark Some public key are created based on the provided private keys - */ - security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_private_key); - /*! - * \brief Constructor based on the public keys only - * \param[in] p_elliptic_curve The ECDSA curve family to be used - * \remark The call to the method security_ecc::sign() will failed - * \remark The call to the method security_ecc::generate() will overwrite the provided public keys - */ - security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y); - /*! - * \brief Constructor based on the public xompressed key only - * \param[in] p_elliptic_curve The ECDSA curve family to be used - * \remark The call to the method security_ecc::sign() will failed - * \remark The call to the method security_ecc::generate() will overwrite the provided public keys - */ - security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_compressed, const ecc_compressed_mode p_compressed_mode); - /*! - * \brief Destructor - */ - virtual ~security_ecc(); - - /*! - * \fn int generate(); - * \brief Generate a pair (PrivateK, PublicK) of keys for signature or encryption - * \return 0 on success, -1 otherwise - * \remark To get the generated keys, \see private_key, public_key_x and public_key_y methods - */ - int generate(); - /*! - * \fn int sign(const OCTETSTRING& p_data, OCTETSTRING& p_r_sig, OCTETSTRING& p_s_sig); - * \brief Signed the data using ECDSA algorithm - * \param[in] p_data The data to be signed - * \param[out] p_r_sig Part of the signature - * \param[out] p_s_sig Part of the signature - * \return 0 on success, -1 otherwise - */ - int sign(const OCTETSTRING &p_data, OCTETSTRING &p_r_sig, OCTETSTRING &p_s_sig); - /*! - * \fn int sign_verif(const OCTETSTRING& p_data, const OCTETSTRING& p_signature); - * \brief Verifiy an ECDSA signature - * \param[in] p_data The signed data - * \param[in] p_signature The signature part, based on r_sig part and s_sig part - * \return 0 on success, -1 otherwise - */ - int sign_verif(const OCTETSTRING &p_data, const OCTETSTRING &p_signature); - - /*! - * \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 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 \remark To get the secret key, uses \see - * secret_key method \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method \remark To get the generated nonce - * vector, uses \see nonce method \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, 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_ephemeral_public_key_x The recipient - * public key X-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_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); - * \brief Encryption using the specified algorithm, the encryption parameters are generated automatically. - * \param[in] p_enc_algorithm The algorithm to use for the encryption - * \param[in] p_message The message to be encrypted - * \param[out] p_enc_message The encrypted message - * \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method - * \remark To get the generated nonce vector, uses \see nonce method - * \remark To get the generated tag, uses \see tag method - * \return 0 on success, -1 otherwise - */ - int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_message, OCTETSTRING &p_enc_message); - /*! - * \fn int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_symmetric_key, const OCTETSTRING& p_nonce, const OCTETSTRING& p_message, - * OCTETSTRING& p_enc_message); \brief Encryption using the specified algorithm. The encryption parameters are provided by the caller (e.g. ECIES encryption). - * \param[in] p_enc_algorithm The algorithm to use for the encryption - * \param[in] p_symmetric_key - * \param[in] p_nonce - * \param[in] p_message The message to be encrypted - * \param[out] p_enc_message The encrypted message - * \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method - * \remark To get the generated nonce vector, uses \see nonce method - * \remark To get the generated tag, uses \see tag method - * \return 0 on success, -1 otherwise - */ - int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_symmetric_key, const OCTETSTRING &p_nonce, const OCTETSTRING &p_message, - OCTETSTRING &p_enc_message); - /*! - * \fn int decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_key, const OCTETSTRING& p_nonce, const OCTETSTRING& p_tag, const - * OCTETSTRING& p_enc_message, OCTETSTRING& p_message); \brief Decryption using the specified parameters. \param[in] p_enc_algorithm The algorithm to use for - * the decryption \param[in] p_nonce The algorithm to use for the encryption \param[in] p_tag The algorithm to use for the encryption \param[in] p_enc_message - * The message to be decrypted \param[out] p_message The decrypted message \remark To get the generated symmetric encryption key, uses \see - * symmetric_encryption_key method \remark To get the generated nonce vector, uses \see nonce method \remark To get the generated tag, uses \see tag method - * \return 0 on success, -1 otherwise - */ - int decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_symmetric_key, const OCTETSTRING &p_nonce, const OCTETSTRING &p_tag, - const OCTETSTRING &p_enc_message, OCTETSTRING &p_message); - /*! - * \fn int decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_key, const OCTETSTRING& p_nonce, const OCTETSTRING& p_tag, const - * OCTETSTRING& p_enc_message, OCTETSTRING& p_message); \brief Decryption using default parameters. \param[in] p_tag The algorithm to use for the encryption - * \param[in] p_enc_message The message to be decrypted - * \param[out] p_message The decrypted message - * \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method - * \remark To get the generated nonce vector, uses \see nonce method - * \remark To get the generated tag, uses \see tag method - * \return 0 on success, -1 otherwise - */ - int decrypt(const OCTETSTRING &p_tag, const OCTETSTRING &p_enc_message, OCTETSTRING &p_message); - - inline const OCTETSTRING & private_key() const { return _pri_key; }; - inline const OCTETSTRING & public_key_x() const { return _pub_key_x; }; - inline const OCTETSTRING & public_key_y() const { return _pub_key_y; }; - inline const OCTETSTRING & public_key_compressed() const { return _pub_key_compressed; }; - inline const ecc_compressed_mode &public_key_compressed_mode() const { return _pub_key_compressed_mode; }; - inline const OCTETSTRING & secret_key() const { return _secret_key; }; - inline const OCTETSTRING & encryption_key_x() const { return _enc_key_x; }; - 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; }; - -private: //! \privatesection - /*! - * \fn const int init(); - * \brief Called by the constructors to set up encryption environment - * \return 0 on success, -1 otherwise - */ - const int init(); - /*! - * \fn int bin_to_ec_point(const OCTETSTRING& p_public_key_x, const OCTETSTRING& p_public_key_y, EC_POINT** p_ec_point); - * \brief Convert a big number object into a public key - * \return 0 on success, -1 otherwise - */ - int bin_to_ec_point(const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, EC_POINT **p_ec_point); - /*! - * \fn int public_key_to_bin(OCTETSTRING& p_bin_key); - * \brief Convert a public key into a big number object - * \return 0 on success, -1 otherwise - */ - int public_key_to_bin(OCTETSTRING &p_bin_key); - - 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 +/*! + * \file security_ecc.hh + * \brief Header file for Elliptic Curve Cryptography. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +class OCTETSTRING; //! TITAN forward declaration + +/*! + * \enum Supported Elliptic curves + */ +enum class ec_elliptic_curves : unsigned char { // TODO Renamed into ecc_elliptic_curves + nist_p_256, /*!< NIST P-256, P-256, primve256v1 */ + brainpool_p_256_r1, /*!< Brainpool P256r1 */ + brainpool_p_384_r1 /*!< Brainpool P384r1 */ +}; // End of class ecc_elliptic_curves + +/*! + * \enum Public key coordinates compression mode + */ +enum class ecc_compressed_mode : unsigned char { + compressed_y_0, /*!< The last significant bit of Y-coodinate ended with 0 */ + compressed_y_1 /*!< The last significant bit of Y-coodinate ended with 1 */ +}; // End of class ecc_compressed_mode + +/*! + * \enum Supported encryption algorithem + */ +enum class encryption_algotithm : unsigned char { // TODO Renamed into ecc_encryption_algotithm + aes_128_ccm, + aes_256_ccm, + aes_128_gcm, + aes_256_gcm +}; // End of class ecc_encryption_algotithm + +/*! + * \class security_ecc + * \brief This class implements the generation of a key pair private/public + */ +class security_ecc { + ec_elliptic_curves _elliptic_curve; /*!< Selected elleptic curve */ + encryption_algotithm _encryption_algotithm; /*!< Selected encryption algotithm */ + EC_KEY * _ec_key; /*!< EC_KEY reference */ + const EC_GROUP * _ec_group; /*!< EC_GROUP reference */ + BN_CTX * _bn_ctx; /*!< Pre-alocated memory used to increase OpenSSL processing */ + OCTETSTRING _pri_key; /*!< Private key storage */ + OCTETSTRING _pub_key_x; /*!< Public key X-coordinate storage */ + OCTETSTRING _pub_key_y; /*!< Public key Y-coordinate storage */ + OCTETSTRING _pub_key_compressed; /*!< Public key compressed */ + ecc_compressed_mode _pub_key_compressed_mode; /*!< Public key coordinates compression mode */ + OCTETSTRING _secret_key; /*!< Shared secret key generated by ECIES encryption method */ + OCTETSTRING _enc_key_x; /*!< Ephemeral public key X-coordinate storage */ + OCTETSTRING _enc_key_y; /*!< Ephemeral public key Y-coordinate storage */ + OCTETSTRING _sym_key; /*!< AES symmetric encryption key generated by encryption method */ + OCTETSTRING _enc_sym_key; /*!< Encrypted AES symmetric encryption key generated by encryption method */ + OCTETSTRING _nonce; /*!< Initial Vector generated by encryption method */ + OCTETSTRING _tag; /*!< Tag vector generated by encryption method */ + +public: //! \publicsection + /*! + * \brief Default constructor + * \param[in] p_elliptic_curve The ECDSA curve family to be used + * \remark Call the method security_ecc::generate() to initialise the private/public key pair + */ + security_ecc(const ec_elliptic_curves p_elliptic_curve); + /*! + * \brief Constructor based on the private key only + * \param[in] p_elliptic_curve The ECDSA curve family to be used + * \param[in] p_private_key The private key + * \remark Some public key are created based on the provided private keys + */ + security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_private_key); + /*! + * \brief Constructor based on the public keys only + * \param[in] p_elliptic_curve The ECDSA curve family to be used + * \remark The call to the method security_ecc::sign() will failed + * \remark The call to the method security_ecc::generate() will overwrite the provided public keys + */ + security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y); + /*! + * \brief Constructor based on the public xompressed key only + * \param[in] p_elliptic_curve The ECDSA curve family to be used + * \remark The call to the method security_ecc::sign() will failed + * \remark The call to the method security_ecc::generate() will overwrite the provided public keys + */ + security_ecc(const ec_elliptic_curves p_elliptic_curve, const OCTETSTRING &p_public_key_compressed, const ecc_compressed_mode p_compressed_mode); + /*! + * \brief Destructor + */ + virtual ~security_ecc(); + + /*! + * \fn int generate(); + * \brief Generate a pair (PrivateK, PublicK) of keys for signature or encryption + * \return 0 on success, -1 otherwise + * \remark To get the generated keys, \see private_key, public_key_x and public_key_y methods + */ + int generate(); + /*! + * \fn int sign(const OCTETSTRING& p_data, OCTETSTRING& p_r_sig, OCTETSTRING& p_s_sig); + * \brief Signed the data using ECDSA algorithm + * \param[in] p_data The data to be signed + * \param[out] p_r_sig Part of the signature + * \param[out] p_s_sig Part of the signature + * \return 0 on success, -1 otherwise + */ + int sign(const OCTETSTRING &p_data, OCTETSTRING &p_r_sig, OCTETSTRING &p_s_sig); + /*! + * \fn int sign_verif(const OCTETSTRING& p_data, const OCTETSTRING& p_signature); + * \brief Verifiy an ECDSA signature + * \param[in] p_data The signed data + * \param[in] p_signature The signature part, based on r_sig part and s_sig part + * \return 0 on success, -1 otherwise + */ + int sign_verif(const OCTETSTRING &p_data, const OCTETSTRING &p_signature); + + /*! + * \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 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 \remark To get the secret key, uses \see + * secret_key method \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method \remark To get the generated nonce + * vector, uses \see nonce method \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, 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_ephemeral_public_key_x The recipient + * public key X-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_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); + * \brief Encryption using the specified algorithm, the encryption parameters are generated automatically. + * \param[in] p_enc_algorithm The algorithm to use for the encryption + * \param[in] p_message The message to be encrypted + * \param[out] p_enc_message The encrypted message + * \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method + * \remark To get the generated nonce vector, uses \see nonce method + * \remark To get the generated tag, uses \see tag method + * \return 0 on success, -1 otherwise + */ + int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_message, OCTETSTRING &p_enc_message); + /*! + * \fn int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_symmetric_key, const OCTETSTRING& p_nonce, const OCTETSTRING& p_message, + * OCTETSTRING& p_enc_message); \brief Encryption using the specified algorithm. The encryption parameters are provided by the caller (e.g. ECIES encryption). + * \param[in] p_enc_algorithm The algorithm to use for the encryption + * \param[in] p_symmetric_key + * \param[in] p_nonce + * \param[in] p_message The message to be encrypted + * \param[out] p_enc_message The encrypted message + * \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method + * \remark To get the generated nonce vector, uses \see nonce method + * \remark To get the generated tag, uses \see tag method + * \return 0 on success, -1 otherwise + */ + int encrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_symmetric_key, const OCTETSTRING &p_nonce, const OCTETSTRING &p_message, + OCTETSTRING &p_enc_message); + /*! + * \fn int decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_key, const OCTETSTRING& p_nonce, const OCTETSTRING& p_tag, const + * OCTETSTRING& p_enc_message, OCTETSTRING& p_message); \brief Decryption using the specified parameters. \param[in] p_enc_algorithm The algorithm to use for + * the decryption \param[in] p_nonce The algorithm to use for the encryption \param[in] p_tag The algorithm to use for the encryption \param[in] p_enc_message + * The message to be decrypted \param[out] p_message The decrypted message \remark To get the generated symmetric encryption key, uses \see + * symmetric_encryption_key method \remark To get the generated nonce vector, uses \see nonce method \remark To get the generated tag, uses \see tag method + * \return 0 on success, -1 otherwise + */ + int decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING &p_symmetric_key, const OCTETSTRING &p_nonce, const OCTETSTRING &p_tag, + const OCTETSTRING &p_enc_message, OCTETSTRING &p_message); + /*! + * \fn int decrypt(const encryption_algotithm p_enc_algorithm, const OCTETSTRING& p_key, const OCTETSTRING& p_nonce, const OCTETSTRING& p_tag, const + * OCTETSTRING& p_enc_message, OCTETSTRING& p_message); \brief Decryption using default parameters. \param[in] p_tag The algorithm to use for the encryption + * \param[in] p_enc_message The message to be decrypted + * \param[out] p_message The decrypted message + * \remark To get the generated symmetric encryption key, uses \see symmetric_encryption_key method + * \remark To get the generated nonce vector, uses \see nonce method + * \remark To get the generated tag, uses \see tag method + * \return 0 on success, -1 otherwise + */ + int decrypt(const OCTETSTRING &p_tag, const OCTETSTRING &p_enc_message, OCTETSTRING &p_message); + + inline const OCTETSTRING & private_key() const { return _pri_key; }; + inline const OCTETSTRING & public_key_x() const { return _pub_key_x; }; + inline const OCTETSTRING & public_key_y() const { return _pub_key_y; }; + inline const OCTETSTRING & public_key_compressed() const { return _pub_key_compressed; }; + inline const ecc_compressed_mode &public_key_compressed_mode() const { return _pub_key_compressed_mode; }; + inline const OCTETSTRING & secret_key() const { return _secret_key; }; + inline const OCTETSTRING & encryption_key_x() const { return _enc_key_x; }; + 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; }; + +private: //! \privatesection + /*! + * \fn const int init(); + * \brief Called by the constructors to set up encryption environment + * \return 0 on success, -1 otherwise + */ + const int init(); + /*! + * \fn int bin_to_ec_point(const OCTETSTRING& p_public_key_x, const OCTETSTRING& p_public_key_y, EC_POINT** p_ec_point); + * \brief Convert a big number object into a public key + * \return 0 on success, -1 otherwise + */ + int bin_to_ec_point(const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, EC_POINT **p_ec_point); + /*! + * \fn int public_key_to_bin(OCTETSTRING& p_bin_key); + * \brief Convert a public key into a big number object + * \return 0 on success, -1 otherwise + */ + int public_key_to_bin(OCTETSTRING &p_bin_key); + + 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 58b5ac6c87f2f2de6fe7664451f2adfb4c7654d7..04e0b9b28c050be297e75cc97345a5b57e3321b6 100644 --- a/ccsrc/Protocols/Security/security_services.cc +++ b/ccsrc/Protocols/Security/security_services.cc @@ -1,1413 +1,1413 @@ -#include - -#include - -#include "security_services.hh" - -using namespace std; // Required for isnan() -#include "etsi_ts103097_certificate_codec.hh" -#include "etsi_ts103097_data_codec.hh" -#include "etsi_ts103097_tobesigned_data_codec.hh" - -#include "security_ecc.hh" -#include "sha256.hh" -#include "sha384.hh" - -#include "base_time.hh" - -#include "params.hh" - -#include "loggers.hh" - -#include "converter.hh" - -security_services *security_services::instance = nullptr; - -security_services::security_services() - : _setup_done{false}, _ec_keys_enc(nullptr), _security_cache(new security_cache), _security_db(nullptr), _last_generation_time(0), - _unknown_certificate(0, nullptr), _requested_certificate(), _latitude(0), _longitude(0), _elevation(0), _geospacial() { - loggers::get_instance().log(">>> security_services::security_services"); - - //_geospacial.load_countries_map("/home/yann/dev/TTF0002_Its/ne-countries-50m.json"); // FIXME Use parameter - -} // End of ctor - -int security_services::setup(params &p_params) { // FIXME Rename this method - loggers::get_instance().log(">>> security_services::setup"); - _params = p_params; - _params.log(); - - if (_setup_done) { - loggers::get_instance().warning("security_services::setup: Already done"); - return 0; - } - - // Build the certificate caching - try { - _security_db.reset(new security_db(_params[params::sec_db_path])); - if (_security_db.get() == nullptr) { // Memory allocation issue - loggers::get_instance().warning("security_services::setup: _security_db pointer is NULL"); - return -1; - } - _setup_done = true; - } catch (...) { - loggers::get_instance().error("security_services::setup: Filesystem access error, terminate test suite on TTCN-3 error. Please check user name and paths " - "in the test suite configuration file."); - return -1; - } - - // Initialise encryption mechanism - params::const_iterator it = _params.find(params::cypher); - if (it == _params.cend()) { - _ec_keys_enc.reset(new security_ecc(ec_elliptic_curves::nist_p_256)); - _params.insert(std::pair(params::cypher, std::string("NISTP-256"))); - p_params.insert(std::pair(params::cypher, std::string("NISTP-256"))); - } else if (it->second.compare("NISTP-256")) { - _ec_keys_enc.reset(new security_ecc(ec_elliptic_curves::nist_p_256)); - } else if (it->second.compare("BP-256")) { - _ec_keys_enc.reset(new security_ecc(ec_elliptic_curves::brainpool_p_256_r1)); - } else { - loggers::get_instance().warning("security_services::setup: Failed to encode ToBeSignedData"); - return -1; - } - - return 0; -} - -int security_services::store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, - const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_comp_key, - const INTEGER &p_public_comp_key_mode, const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, - const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, const OCTETSTRING &p_private_enc_key, - const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, - const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_key_compressed_mode) { - loggers::get_instance().log_msg(">>> security_services::store_certificate: ", p_cert_id); - - // Sanity checks - if (_security_db.get() == nullptr) { // Setup not called - loggers::get_instance().warning("security_services::store_certificate: Not initialised"); - return -1; - } - return _security_db.get()->store_certificate(p_cert_id, p_cert, p_private_key, p_public_key_x, p_public_key_y, p_public_comp_key, p_public_comp_key_mode, - p_hash, p_hash_sha_256, p_hashid8, p_issuer, p_private_enc_key, p_public_enc_key_x, p_public_enc_key_y, - p_public_enc_compressed_key, p_public_enc_key_compressed_mode); -} - -int security_services::verify_and_extract_gn_payload(const OCTETSTRING &p_secured_gn_payload, const bool p_verify, - Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, OCTETSTRING &p_unsecured_gn_payload, - params &p_params) { - loggers::get_instance().log_msg(">>> security_services::verify_and_extract_gn_payload: ", p_secured_gn_payload); - - // Sanity checks - if (p_secured_gn_payload.lengthof() == 0) { - return -1; - } - - // Decode the secured message (OER encoding) - etsi_ts103097_data_codec codec; - codec.decode(p_secured_gn_payload, p_ieee_1609dot2_data, &p_params); - // Sanity checks - if (!p_ieee_1609dot2_data.is_bound()) { - loggers::get_instance().warning("security_services::verify_and_extract_gn_payload: Unbound value, discard it"); - return -1; - } - if (p_verify && ((unsigned int)(int)p_ieee_1609dot2_data.protocolVersion() != security_services::ProtocolVersion)) { - loggers::get_instance().warning("security_services::verify_and_extract_gn_payload: Wrong version protocol, discard it"); - return -1; - } - - return process_ieee_1609_dot2_content(p_ieee_1609dot2_data.content(), p_verify, p_unsecured_gn_payload, p_params); -} // End of method verify_and_extract_gn_payload - -int security_services::process_ieee_1609_dot2_content(const Ieee1609Dot2::Ieee1609Dot2Content &p_ieee_1609_dot2_content, const bool p_verify, - OCTETSTRING &p_unsecured_payload, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::process_ieee_1609_dot2_content: ", p_ieee_1609_dot2_content); - - if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_unsecuredData)) { // Unsecured packet, End of recursivity - p_unsecured_payload = p_ieee_1609_dot2_content.unsecuredData(); - } else if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_signedData)) { - const Ieee1609Dot2::SignedData &signedData = p_ieee_1609_dot2_content.signedData(); - if (process_ieee_1609_dot2_signed_data(signedData, p_verify, p_unsecured_payload, p_params) != 0) { - if (p_verify) { - return -1; - } - } - } else if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_encryptedData)) { - const Ieee1609Dot2::EncryptedData &encrypted_data = p_ieee_1609_dot2_content.encryptedData(); - OCTETSTRING signed_payload; - if (process_ieee_1609_dot2_encrypted_data(encrypted_data, p_verify, signed_payload, p_params) != 0) { - return -1; - } - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_content: Decrypted payload: ", signed_payload); - Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data; // TODO Check if it could be reused - if (verify_and_extract_gn_payload(signed_payload, p_verify, ieee_1609dot2_data, p_unsecured_payload, p_params) != 0) { - if (p_verify) { - return -1; - } - } - } else if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_signedCertificateRequest)) { - // Reset certificate timer - loggers::get_instance().log("security_services::process_ieee_1609_dot2_content: Set Certificate re-transmission flag and reset timer"); - _last_generation_time = 0; - return 0; - } else { // Shall never be reached - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_content: Undefined IEEE 1609.2 Content, discard it"); - if (p_verify) { - return -1; - } - } - - loggers::get_instance().log_msg("<<< security_services::process_ieee_1609_dot2_content: ", p_unsecured_payload); - return 0; -} // End of method process_ieee_1609_dot2_content - -int security_services::process_ieee_1609_dot2_signed_data(const Ieee1609Dot2::SignedData &p_signed_data, const bool p_verify, OCTETSTRING &p_unsecured_payload, - params &p_params) { - loggers::get_instance().log_msg(">>> security_services::process_ieee_1609_dot2_signed_data: ", p_signed_data); - - // Check the headerInfo content - const Ieee1609Dot2::HeaderInfo &header_info = p_signed_data.tbsData().headerInfo(); - p_params[params::its_aid] = std::to_string(header_info.psid().get_long_long_val()); - if (!header_info.generationTime().is_present()) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: HeaderInfo::GenerationTime field is missing"); - if (p_verify) { - return -1; - } - } else { - const OPTIONAL &v = dynamic_cast &>(header_info.generationTime()); // in microsecond - unsigned long long gt = ((INTEGER &)(*v.get_opt_value())).get_long_long_val(); - // Get current time timestamp - unsigned long long us = base_time::get_instance().get_its_current_time_us(); // in microsecond - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: generation time check %ld / %ld, delta = %f", gt, us, - abs((double)gt - (double)us)); - if (abs((double)gt - (double)us) >= 5000000.0) { // TODO Use a params for generation_time_epsilon, 5s differences - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Invalid generation time, discard it"); - if (p_verify) { - return -1; - } - } - } - - // Check p2pcdLearningRequest keys if present - if (header_info.p2pcdLearningRequest().is_present()) { - loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: p2pcdLearningRequest not supported yet"); - // TODO Not supported by C-ITS Protocol - } - - // Check missingCrlIdentifier keys if present - if (header_info.missingCrlIdentifier().is_present()) { - loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: missingCrlIdentifier not supported yet"); - // TODO Not supported by C-ITS Protocol - } - - // Check encryption keys if present - if (header_info.encryptionKey().is_present()) { - loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: encryptionKey not supported yet"); - // TODO Not supported by C-ITS Protocol - } - - // Check request certificate - if (header_info.inlineP2pcdRequest().is_present()) { - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: inlineP2pcdRequest: ", header_info.inlineP2pcdRequest()); - const Ieee1609Dot2BaseTypes::SequenceOfHashedId3 &s = - static_cast(*header_info.inlineP2pcdRequest().get_opt_value()); - _requested_certificate.clear(); - for (int i = 0; i < s.lengthof(); i++) { - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: Add requested certificate= ", s[i]); - _requested_certificate.push_back(s[i]); - } // End of 'for' statement - } - - // Check requested certificate - if (header_info.requestedCertificate().is_present()) { - loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: requestedCertificate not supported yet"); - // TODO Not supported by C-ITS Protocol - } - - // Check and extract unsecured payload - if (p_signed_data.tbsData().payload().data().is_present()) { - // Check protocol version - const OPTIONAL &v = - dynamic_cast &>(p_signed_data.tbsData().payload().data()); - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: SignedDataPayload.data=", v); - const Ieee1609Dot2::Ieee1609Dot2Data &ieee_1609dot2_data = static_cast(*v.get_opt_value()); - if (p_verify && ((unsigned int)(int)ieee_1609dot2_data.protocolVersion() != security_services::ProtocolVersion)) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Wrong version protocol, discard it"); - if (p_verify) { - return -1; - } - } - if (process_ieee_1609_dot2_content(ieee_1609dot2_data.content(), p_verify, p_unsecured_payload, p_params) != 0) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to process SignedData, discard it"); - if (p_verify) { - return -1; - } - } - } else if (p_signed_data.tbsData().payload().extDataHash().is_present()) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unsupported extDataHash, discard it"); - if (p_verify) { - return -1; - } - } else { // Shall not be reached - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unsupported SignedDataPayload, discard it"); - return -1; - } - - // Encode the ToBeSignedData - etsi_ts103097_tobesigned_data_codec tbs_data_codec; - OCTETSTRING os; - tbs_data_codec.encode(p_signed_data.tbsData(), os); - if (os.lengthof() == 0) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to encode ToBeSignedData"); - return -1; - } - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: encoded tbs_data=", os); - // Calculate the hash according to the hashId - OCTETSTRING hashed_data; - if (p_signed_data.hashId() == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { - hash_sha256(os, hashed_data); - } else { - hash_sha384(os, hashed_data); - } - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: hashed_data=", hashed_data); - // Retrieve certificate identifier - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: signer=", p_signed_data.signer()); - std::string certificate_id; - int result = -1; - if (p_signed_data.signer().ischosen(Ieee1609Dot2::SignerIdentifier::ALT_digest)) { - // Retrieve the certificate identifier from digest - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: Retrieve the certificate identifier from digest"); - result = _security_db.get()->get_certificate_id(p_signed_data.signer().digest(), certificate_id); - if (result == -1) { - // Check in the cache - if (_security_cache.get()->get_certificate_id(p_signed_data.signer().digest(), certificate_id) == -1) { - // Unknown certificate, request it - const OCTETSTRING &os = p_signed_data.signer().digest(); - _unknown_certificate = OCTETSTRING(3, static_cast(os) + os.lengthof() - 3); - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unknown certificate, request it"); - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: HashedId3: ", _unknown_certificate); - } - // Reset certificate timer - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: Set Certificate re-transmission flag and reset timer"); - _last_generation_time = 0; - - return -1; - } - } else if (p_signed_data.signer().ischosen(Ieee1609Dot2::SignerIdentifier::ALT_certificate) && (p_signed_data.signer().certificate().size_of() != 0)) { - // Extract the certificates - std::vector certificate_ids; - for (int i = 0; i < p_signed_data.signer().certificate().size_of(); i++) { - Ieee1609Dot2::CertificateBase cert = p_signed_data.signer().certificate()[i]; - // Retrieve ssps - OPTIONAL &v = cert.toBeSigned().appPermissions(); - if (v.is_present()) { - Ieee1609Dot2BaseTypes::SequenceOfPsidSsp psid_ssps = static_cast(*v.get_opt_value()); - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: psid_ssps size: %d", psid_ssps.lengthof()); - for (int i = 0; i < psid_ssps.lengthof(); i++) { - const Ieee1609Dot2BaseTypes::PsidSsp &psid_ssp = psid_ssps[i]; - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: Processing psid_ssp ", psid_ssp); - const OPTIONAL &s = psid_ssp.ssp(); - if (s.is_present()) { - const Ieee1609Dot2BaseTypes::ServiceSpecificPermissions &ssp = static_cast(s); - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: Processing ssp ", ssp); - params::const_iterator it = p_params.find(std::to_string(psid_ssp.psid())); - if (it == p_params.cend()) { - OCTETSTRING os; - if (ssp.ischosen(Ieee1609Dot2BaseTypes::ServiceSpecificPermissions::ALT_opaque)) { - os = ssp.opaque(); - } else { - os = ssp.bitmapSsp(); - } - p_params[params::ssp] = std::string(static_cast(oct2str(os))); - } - } - } // End of 'for' statement - } - - std::string certificate_id; - if (extract_and_store_certificate(cert, certificate_id) != 0) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to store certificate"); - if (p_verify) { - return -1; - } - } - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: certificate_id: '%s'", certificate_id.c_str()); - certificate_ids.push_back(certificate_id); - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: certificate_ids size: %d", certificate_ids.size()); - } // End of 'for' statement - certificate_id = certificate_ids[0]; - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: After extract_and_store_certificate, certificate_id: '%s'", - certificate_id.c_str()); - } else { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unsupported SignerIdentifier"); - return -1; - } - loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: certificate id = '%s'", certificate_id.c_str()); - // Verify the signature of the ToBeSignedData - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: signature=", p_signed_data.signature__()); - result = -1; - if (p_signed_data.signature__().ischosen(Ieee1609Dot2BaseTypes::Signature::ALT_ecdsaNistP256Signature)) { - result = verify_sign_ecdsa_nistp256(hashed_data, p_signed_data.signature__(), certificate_id, p_params); - } else if (p_signed_data.signature__().ischosen(Ieee1609Dot2BaseTypes::Signature::ALT_ecdsaBrainpoolP256r1Signature)) { - result = verify_sign_ecdsa_brainpoolp256r1(hashed_data, p_signed_data.signature__(), certificate_id, p_params); - } else if (p_signed_data.signature__().ischosen(Ieee1609Dot2BaseTypes::Signature::ALT_ecdsaBrainpoolP384r1Signature)) { - result = verify_sign_ecdsa_brainpoolp384r1(hashed_data, p_signed_data.signature__(), certificate_id, p_params); - } else { - // TODO - loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: TODO"); - } - if (result != 0) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to verify signature"); - return -1; - } - - loggers::get_instance().log_msg("<<< security_services::process_ieee_1609_dot2_signed_data: ", p_unsecured_payload); - return 0; -} // End of method process_ieee_1609_dot2_signed_data - -int security_services::process_ieee_1609_dot2_encrypted_data(const Ieee1609Dot2::EncryptedData &p_encrypted_data, const bool p_verify, - OCTETSTRING &p_unsecured_payload, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::process_ieee_1609_dot2_encrypted_data: ", p_encrypted_data); - - // 1. Retrieve the RecipientId - const Ieee1609Dot2::RecipientInfo & r = p_encrypted_data.recipients()[0]; // TODO Add multiple support of recipients - const Ieee1609Dot2BaseTypes::EciesP256EncryptedKey *ecies = nullptr; // TODO Use smart pointer - const OCTETSTRING * recipient_id = nullptr; // TODO Use smart pointer - if (r.ischosen(Ieee1609Dot2::RecipientInfo::ALT_certRecipInfo)) { - recipient_id = &r.certRecipInfo().recipientId(); - if (r.certRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesNistP256)) { - ecies = &r.certRecipInfo().encKey().eciesNistP256(); - } else if (r.certRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesBrainpoolP256r1)) { - ecies = &r.certRecipInfo().encKey().eciesBrainpoolP256r1(); - } else { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported encryption algorithm"); - return -1; - } - } else if (r.ischosen(Ieee1609Dot2::RecipientInfo::ALT_signedDataRecipInfo)) { - recipient_id = &r.signedDataRecipInfo().recipientId(); - if (r.signedDataRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesNistP256)) { - ecies = &r.signedDataRecipInfo().encKey().eciesNistP256(); - } else if (r.signedDataRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesBrainpoolP256r1)) { - ecies = &r.signedDataRecipInfo().encKey().eciesBrainpoolP256r1(); - } else { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported encryption algorithm"); - return -1; - } - } else { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported RecipientInfo variant"); - return -1; - } - if (!p_encrypted_data.ciphertext().ischosen(Ieee1609Dot2::SymmetricCiphertext::ALT_aes128ccm)) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported AES 128 algorithm"); - return -1; - } - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: RecipientId= ", *recipient_id); - - // 2. Retrieve the certificate if present - std::string certificate_id; - OCTETSTRING p_enc_key; // The private encryption key - if (_security_db.get()->get_certificate_id(*recipient_id, certificate_id) == -1) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unknown certificate"); - // Check if RecipientId is the hashed_id8 of the symetric AES keys - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: AES Symmetric Keys= ", ecies->c()); - OCTETSTRING hashed_data; - hash_sha256(ecies->c(), hashed_data); - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: Hash (AES Symmetric Keys)= ", hashed_data); - if (substr(hashed_data, hashed_data.lengthof() - 8, 8) != *recipient_id) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: RecipientId does not match HashedId8 of the symmetric key"); - return -1; - } else { - if (_security_db.get()->get_private_enc_key(p_params[params::certificate], p_enc_key) == -1) { - loggers::get_instance().warning( - "security_services::process_ieee_1609_dot2_encrypted_data: Failed to retrieve private encryption key for certificate %s", - p_params[params::certificate].c_str()); - return -1; - } - } - } else { - if (_security_db.get()->get_private_enc_key(certificate_id, p_enc_key) == -1) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to retrieve private encryption key"); - return -1; - } - } - - // 3. Generate the shared secret value based on recipient's public ephemeral keys will be required - 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, 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)) { - 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)) { - 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; - } - if (result == -1) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to generate shared secret"); - return -1; - } - // 4. Decrypt the message - OCTETSTRING enc_message(p_encrypted_data.ciphertext().aes128ccm().ccmCiphertext().lengthof() - ec.tag().lengthof(), - static_cast(p_encrypted_data.ciphertext().aes128ccm().ccmCiphertext())); - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: enc_message: ", enc_message); - OCTETSTRING tag(ec.tag().lengthof(), enc_message.lengthof() + static_cast(p_encrypted_data.ciphertext().aes128ccm().ccmCiphertext())); - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: tag: ", tag); - if (ec.decrypt(tag, enc_message, p_unsecured_payload) == -1) { - loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to generate shared secret"); - return -1; - } - loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: ", p_unsecured_payload); - - return 0; -} // End of method process_ieee_1609_dot2_encrypted_data - -int security_services::secure_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_secured_gn_payload, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::secure_gn_payload: ", p_unsecured_gn_payload); - p_params.log(); - - OCTETSTRING signed_payload; - if (sign_payload(p_unsecured_gn_payload, signed_payload, p_params) != 0) { - p_secured_gn_payload = p_unsecured_gn_payload; - loggers::get_instance().warning("security_services::secure_gn_payload: Failed to signed payload"); - return -1; - } - - if (_params[params::encrypted_mode].compare("1") == 0) { - if (encrypt_gn_payload(signed_payload, p_secured_gn_payload, p_params) != 0) { - p_secured_gn_payload = signed_payload; - loggers::get_instance().warning("security_services::secure_gn_payload: Failed to encrypt payload"); - return -1; - } - } else { // No encryption required - loggers::get_instance().log("security_services::secure_gn_payload: Encryption mode not set"); - p_secured_gn_payload = signed_payload; - } - - return 0; -} - -int security_services::sign_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_signed_gn_payload, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::sign_payload: ", p_unsecured_gn_payload); - - // Set unsecured data - Ieee1609Dot2::Ieee1609Dot2Content unsecured_data_content; - unsecured_data_content.unsecuredData() = p_unsecured_gn_payload; - Ieee1609Dot2::Ieee1609Dot2Data unsecured_data(ProtocolVersion, unsecured_data_content); - // Set hash algorithm - Ieee1609Dot2BaseTypes::HashAlgorithm hashId(Ieee1609Dot2BaseTypes::HashAlgorithm::sha256); - if (p_params[params::hash].compare("SHA-384") == 0) { - hashId = Ieee1609Dot2BaseTypes::HashAlgorithm::sha384; - } - // Set SignedDataPayload - Ieee1609Dot2::SignedDataPayload payload; - payload.data() = unsecured_data; - payload.extDataHash().set_to_omit(); - Ieee1609Dot2::HeaderInfo header_info; - // Set secured field according to the payload! - header_info.psid() = converter::get_instance().string_to_int(p_params[params::its_aid]); - header_info.expiryTime().set_to_omit(); - if (p_params[params::its_aid].compare("37") == 0) { // Only used by AtsRSUSimulator to add location header - // Mandatory for DENM payload - OPTIONAL location(Ieee1609Dot2BaseTypes::ThreeDLocation(_latitude, _longitude, _elevation)); - header_info.generationLocation() = location; - loggers::get_instance().log_msg("security_services::sign_payload: generationLocation: ", header_info.generationLocation()); - } else { - header_info.generationLocation().set_to_omit(); - } - header_info.p2pcdLearningRequest().set_to_omit(); - header_info.missingCrlIdentifier().set_to_omit(); - if (_params[params::encrypted_mode].compare("1") == 0) { - // TODO Set the encrytion key. Not supported yet, need to clarify mechanism, see IEEE Std 1609.2-20XX Clause 6.3.9 HeaderInfo - header_info.encryptionKey().set_to_omit(); - } else { - header_info.encryptionKey().set_to_omit(); - } - params::const_iterator it = p_params.find(params::payload_type); - if (it != p_params.cend()) { - loggers::get_instance().log("security_services::sign_payload: Payload type: %s", it->second.c_str()); - if (it->second.compare("1") == 0) { // DENM - OPTIONAL location(Ieee1609Dot2BaseTypes::ThreeDLocation(_latitude, _longitude, _elevation)); - loggers::get_instance().log_msg("security_services::sign_payload: generationLocation: ", location); - header_info.generationLocation() = location; - loggers::get_instance().log_msg("security_services::sign_payload: generationLocation: ", header_info.generationLocation()); - } else if (it->second.compare("2") == 0) { // CAM - // Noting to do - } else { - // Noting to do - } - } else { // Process it as a GeoNetworking payload - loggers::get_instance().log("security_services::sign_payload: Payload type not set"); - // Noting to do - } - unsigned long long us = base_time::get_instance().get_its_current_time_us(); - loggers::get_instance().log("security_services::sign_payload: HeaderInfo timestamp: %ld", us); - INTEGER i; - i.set_long_long_val(us); - header_info.generationTime() = OPTIONAL(i); - loggers::get_instance().log("security_services::sign_payload: Final HeaderInfo timestamp: %ld", us); - // Check if a certificate shall be requested - if (_unknown_certificate.lengthof() == 3) { // HashedId3 of a requested certificate - Ieee1609Dot2BaseTypes::SequenceOfHashedId3 s; - s[0] = _unknown_certificate; - header_info.inlineP2pcdRequest() = OPTIONAL(s); - _unknown_certificate = OCTETSTRING(0, nullptr); - } else { - header_info.inlineP2pcdRequest().set_to_omit(); - } - if (_requested_certificate.size() != 0) { - Ieee1609Dot2::CertificateBase c; - const Ieee1609Dot2BaseTypes::HashedId3 &hashed_id3 = _requested_certificate[0]; - _security_db->get_certificate(hashed_id3, c); - header_info.requestedCertificate() = OPTIONAL(c); - } else { - header_info.requestedCertificate().set_to_omit(); - } - - Ieee1609Dot2::ToBeSignedData tbs_data; - tbs_data.payload() = payload; - tbs_data.headerInfo() = header_info; - loggers::get_instance().log_msg("security_services::sign_payload: tbs_data=", tbs_data); - // Sign the ToBeSignedData data structure - Ieee1609Dot2BaseTypes::Signature signature; - if (sign_tbs_data(tbs_data, hashId, signature, p_params) != 0) { - loggers::get_instance().warning("security_services::sign_payload: Failed to secure payload"); - return -1; - } - Ieee1609Dot2::SignerIdentifier signer; - loggers::get_instance().log("security_services::sign_payload: us = %ld - _last_generation_time = %ld - us - _last_generation_time = %ld", us, - _last_generation_time, us - _last_generation_time); - std::string certificate_id = p_params[params::certificate]; - loggers::get_instance().log("security_services::sign_payload: certificate_id = %s", certificate_id.c_str()); - if ((unsigned int)(us - _last_generation_time) >= 1000000 * 0.95) { // Need to add certificate every 1s - loggers::get_instance().log("security_services::sign_payload: Need to add certificate"); - Ieee1609Dot2::CertificateBase cert; - if (_security_db->get_certificate(certificate_id, cert) != 0) { - loggers::get_instance().warning("security_services:sign_payload: Failed to secure payload"); - return -1; - } - loggers::get_instance().log("security_services::sign_payload: cert= ", cert); - Ieee1609Dot2::SequenceOfCertificate sequenceOfCertificate; - sequenceOfCertificate[0] = cert; - signer.certificate() = sequenceOfCertificate; - // Reset send certificate timer - _last_generation_time = us; - loggers::get_instance().log("security_services::sign_payload: Reset send certificate timer, signer= ", signer); - } else { - loggers::get_instance().log("security_services::sign_payload: Add digest"); - OCTETSTRING digest; - if (_security_db->get_hashed_id(certificate_id, digest) != 0) { - loggers::get_instance().warning("security_services::sign_payload: Failed to secure payload"); - return -1; - } - signer.digest() = digest; - } - Ieee1609Dot2::SignedData signed_data(hashId, tbs_data, signer, signature); - loggers::get_instance().log_msg("security_services::sign_payload: signed_data=", signed_data); - Ieee1609Dot2::Ieee1609Dot2Content ieee_dot2_content; - ieee_dot2_content.signedData() = signed_data; - Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data(security_services::ProtocolVersion, ieee_dot2_content); - loggers::get_instance().log_msg("security_services::sign_payload: ieee_1609dot2_data=", ieee_1609dot2_data); - etsi_ts103097_data_codec codec; - codec.encode(ieee_1609dot2_data, p_signed_gn_payload); - if (!p_signed_gn_payload.is_bound()) { - loggers::get_instance().warning("security_services::sign_payload: Failed to encode Ieee1609Dot2Data"); - return -1; - } - - return 0; -} - -int security_services::encrypt_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_enc_gn_payload, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::encrypt_gn_payload: ", p_unsecured_gn_payload); - - // Sanity checks - if (_ec_keys_enc.get() == nullptr) { - loggers::get_instance().warning("security_services::encrypt_gn_payload: Encryption not initialised"); - return -1; - } - params::const_iterator it = p_params.find(params::peer_certificate); - if (it == p_params.cend()) { - loggers::get_instance().warning("security_services::encrypt_gn_payload: Encryption impossible without a peer_certificte indication in parameters"); - return -1; - } - std::string certificate_id = it->second; - loggers::get_instance().log("security_services::encrypt_gn_payload: Peer CertificateId=%s", certificate_id.c_str()); - - // 1. Retrieve recipient's public keys - OCTETSTRING r_public_key_x; - OCTETSTRING r_public_key_y; - if (_security_db.get()->get_public_enc_keys(certificate_id, r_public_key_x, r_public_key_y) == -1) { - loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to retrieve recipient's public keys"); - // TODO Setup request certificate mechanism - return -1; - } - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: r_public_key_x=", r_public_key_x); - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: r_public_key_y=", r_public_key_y); - - // 2. Generate new Private/Public ephemeral keys - if (_ec_keys_enc.get()->generate() == -1) { - loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to generate ephemeral keys"); - return -1; - } - - // 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, OCTETSTRING(0, nullptr)) == -1) { - loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to generate and derive secret key"); - return -1; - } - - // 4. Buil curve data structure in canonical form - Ieee1609Dot2BaseTypes::EccP256CurvePoint eccP256CurvePoint; - if (_ec_keys_enc.get()->public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) { - eccP256CurvePoint.compressed__y__0() = _ec_keys_enc.get()->public_key_compressed(); - } else if (_ec_keys_enc.get()->public_key_compressed_mode() == ecc_compressed_mode::compressed_y_1) { - eccP256CurvePoint.compressed__y__1() = _ec_keys_enc.get()->public_key_compressed(); - } else { - eccP256CurvePoint.uncompressedP256().x() = _ec_keys_enc.get()->public_key_x(); - eccP256CurvePoint.uncompressedP256().y() = _ec_keys_enc.get()->public_key_y(); - } - Ieee1609Dot2BaseTypes::EciesP256EncryptedKey ecies_key(eccP256CurvePoint, _ec_keys_enc.get()->encrypted_symmetric_key(), _ec_keys_enc.get()->tag()); - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: ecies_key=", ecies_key); - - // 5. AES-128 encryption of the data - OCTETSTRING enc_message; - if (_ec_keys_enc.get()->encrypt(encryption_algotithm::aes_128_ccm, _ec_keys_enc.get()->symmetric_encryption_key(), _ec_keys_enc.get()->nonce(), - p_unsecured_gn_payload, enc_message) == -1) { - loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to encrypt message"); - return -1; - } - OCTETSTRING nonce = _ec_keys_enc.get()->nonce(); - OCTETSTRING tag = _ec_keys_enc.get()->tag(); - Ieee1609Dot2::AesCcmCiphertext aes_128_ccm(nonce, enc_message + tag); // Add tag at the end of the ciphered text - // 6. Build SymmetricCiphertext - Ieee1609Dot2::SymmetricCiphertext cipher_text; - cipher_text.aes128ccm() = aes_128_ccm; - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: aes_128_ccm=", cipher_text); - - // 7. Build the recipient_id - OCTETSTRING recipient_id; - _security_db.get()->get_hashed_id(certificate_id, recipient_id); // SHA-256 of the certificate which contain the recipient's public keys - - // 8. Build the encryption data - Ieee1609Dot2::EncryptedDataEncryptionKey enc_data_key; - if (_params[params::cypher].compare("NISTP-256") == 0) { - enc_data_key.eciesNistP256() = ecies_key; - } else if (_params[params::cypher].compare("BP-256") == 0) { - enc_data_key.eciesBrainpoolP256r1() = ecies_key; - } - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: enc_data_key=", enc_data_key); - - // 9. Finalise the encryption - Ieee1609Dot2::PKRecipientInfo cert_recipient_info(recipient_id, enc_data_key); - Ieee1609Dot2::RecipientInfo recipient_info; - recipient_info.certRecipInfo() = cert_recipient_info; - Ieee1609Dot2::SequenceOfRecipientInfo recipients; - recipients[0] = recipient_info; - Ieee1609Dot2::EncryptedData encrypted_data(recipients, cipher_text); - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: encrypted_data=", encrypted_data); - - // 10. Encode it - Ieee1609Dot2::Ieee1609Dot2Content ieee_dot2_content; - ieee_dot2_content.encryptedData() = encrypted_data; - Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data(security_services::ProtocolVersion, ieee_dot2_content); - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: ieee_1609dot2_data=", ieee_1609dot2_data); - etsi_ts103097_data_codec codec; - codec.encode(ieee_1609dot2_data, p_enc_gn_payload); - if (!p_enc_gn_payload.is_bound()) { - loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to encode Ieee1609Dot2Data"); - return -1; - } - loggers::get_instance().log_msg("security_services::encrypt_gn_payload: Encoded ieee_1609dot2_data=", p_enc_gn_payload); - - return 0; -} - -int security_services::decrypt_gn_payload(const OCTETSTRING &p_enc_gn_payload, OCTETSTRING &p_unsecured_gn_payload, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::decrypt_gn_payload: ", p_enc_gn_payload); - - // Sanity checks - if (_ec_keys_enc.get() == nullptr) { - loggers::get_instance().warning("security_services::decrypt_gn_payload: Encryption not initialised"); - return -1; - } - - // 1. Decode the IEEE 1609dot2Data-Encrypted - Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data; - etsi_ts103097_data_codec codec; - codec.decode(p_enc_gn_payload, ieee_1609dot2_data); - if (!ieee_1609dot2_data.is_bound()) { - loggers::get_instance().warning("security_services::decrypt_gn_payload: Failed to decode Ieee1609Dot2Data-Encrypted"); - return -1; - } - loggers::get_instance().log_msg("security_services::decrypt_gn_payload: Ieee1609Dot2Data-Encrypted=", ieee_1609dot2_data); - - if (!ieee_1609dot2_data.content().ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_encryptedData)) { - loggers::get_instance().warning("security_services::decrypt_gn_payload: Failed to decode Decrypt Ieee1609Dot2Data-Encrypted"); - return -1; - } - if (process_ieee_1609_dot2_encrypted_data(ieee_1609dot2_data.content().encryptedData(), true, p_unsecured_gn_payload, p_params) == -1) { - loggers::get_instance().warning("security_services::decrypt_gn_payload: Failed to decode Decrypt Ieee1609Dot2Data-Encrypted"); - return -1; - } - loggers::get_instance().log_msg("security_services::decrypt_gn_payload: Encoded ieee_1609dot2_data=", p_unsecured_gn_payload); - - return 0; -} - -int security_services::sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, - const OCTETSTRING &p_private_key, Ieee1609Dot2BaseTypes::Signature &p_signature, - params &p_params) { // TODO Refine function - loggers::get_instance().log_msg(">>> security_services::sign_tbs_data: ", p_tbs_data); - - // Encode the ToBeSignedData - etsi_ts103097_tobesigned_data_codec tbs_data_codec; - OCTETSTRING os; - tbs_data_codec.encode(p_tbs_data, os); - if (os.lengthof() == 0) { - loggers::get_instance().warning("security_services::sign_tbs_data: Failed to encode ToBeSignedData"); - return -1; - } - loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded tbs_data=", os); - // Hash ToBeSignedData - OCTETSTRING hashed_data; - OCTETSTRING hash_issuer; - if (p_hashAlgorithm == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { - sha256 hash; - hash.generate(os, hashed_data); - hash_issuer = hash.get_sha256_empty_string(); - } else { - sha384 hash; - hash.generate(os, hashed_data); - hash_issuer = hash.get_sha384_empty_string(); - } - loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded hashed_data=", hashed_data); - loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded hashed_issuer=", hash_issuer); - // Sign ToBeSignedData - loggers::get_instance().log("security_services::sign_tbs_data: encoded params::signature = '%s'", - p_params[params::signature].c_str()); // TODO this parameter is useless, use content of the certificate - loggers::get_instance().log("security_services::sign_tbs_data: encoded params::certificate = '%s'", p_params[params::certificate].c_str()); - if (p_params[params::signature].compare("NISTP-256") == 0) { - // Hash ( Hash (Data input) || Hash ("") ) - OCTETSTRING os = hashed_data + hash_issuer; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::sign_tbs_data: hash: ", os); - OCTETSTRING hashed_data; - hash_sha256(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - security_ecc k(ec_elliptic_curves::nist_p_256, p_private_key); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashed_data, r_sig, s_sig) != 0) { - loggers::get_instance().warning("security_services::sign_tbs_data: Failed to sign payload"); - return -1; - } - Ieee1609Dot2BaseTypes::EccP256CurvePoint ep; - ep.x__only() = r_sig; - p_signature.ecdsaNistP256Signature() = Ieee1609Dot2BaseTypes::EcdsaP256Signature(ep, s_sig); - loggers::get_instance().log_msg("security_services::sign_tbs_data: signature=", p_signature); - } // TODO To be done - - return 0; -} - -int security_services::sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, - Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::sign_tbs_data: ", p_tbs_data); - - // Get certificate - loggers::get_instance().log("security_services::sign_tbs_data: encoded params::certificate = '%s'", p_params[params::certificate].c_str()); - // TODO Remove signature paramter, use certificate only, check if it is okay for GN with device_mode set and not setxs - // _security_db.get()->get_certificate(p_params[params::certificate]); - - // Encode the ToBeSignedData - etsi_ts103097_tobesigned_data_codec tbs_data_codec; - OCTETSTRING os; - tbs_data_codec.encode(p_tbs_data, os); - if (os.lengthof() == 0) { - loggers::get_instance().warning("security_services::sign_tbs_data: Failed to encode ToBeSignedData"); - return -1; - } - loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded tbs_data=", os); - // Hash ToBeSignedData - OCTETSTRING hashed_data; - if (p_hashAlgorithm == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { - hash_sha256(os, hashed_data); - } else { - hash_sha384(os, hashed_data); - } - loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded hashed_data=", hashed_data); - // Sign ToBeSignedData - int result = -1; - loggers::get_instance().log("security_services::sign_tbs_data: encoded params::signature = '%s'", - p_params[params::signature].c_str()); // TODO this parameter is useless, use content of the certificate - loggers::get_instance().log("security_services::sign_tbs_data: encoded params::certificate = '%s'", p_params[params::certificate].c_str()); - if (p_params[params::signature].compare("NISTP-256") == 0) { - result = sign_ecdsa_nistp256(hashed_data, p_signature, p_params); - } else if (p_params[params::signature].compare("BP-256") == 0) { - // result = sign_ecdsa_brainpoolp256r1(hashed_data, p_signature, p_params); - loggers::get_instance().error("security_services::sign_tbs_data: TODO"); - result = -1; - } else if (p_params[params::signature].compare("BP-384") == 0) { - // result = sign_ecdsa_brainpoolp384r1(hashed_data, p_signature, p_params); - loggers::get_instance().error("security_services::sign_tbs_data: TODO"); - result = -1; - } else { - loggers::get_instance().error("security_services::sign_tbs_data: Unsupported signature algorithm"); - result = -1; - } - if (result != 0) { - loggers::get_instance().warning("security_services::sign_tbs_data: Failed to sign payload"); - return -1; - } - - return 0; -} - -int security_services::hash_sha256(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data) { - loggers::get_instance().log_msg(">>> security_services::hash_sha256: ", p_data); - - sha256 hash; - return hash.generate(p_data, p_hash_data); -} - -int security_services::hash_sha384(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data) { - loggers::get_instance().log_msg(">>> security_services::hash_sha384: ", p_data); - - sha384 hash; - return hash.generate(p_data, p_hash_data); -} - -int security_services::sign_ecdsa_nistp256(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::sign_ecdsa_nistp256: ", p_hash); - - std::string certificate_id = p_params[params::certificate]; - loggers::get_instance().log("security_services::sign_ecdsa_nistp256: encoded certificate_id = '%s'", certificate_id.c_str()); - OCTETSTRING pkey; - if (_security_db->get_private_key(certificate_id, pkey) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_nistp256: Failed to get private key"); - return -1; - } - // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - OCTETSTRING hash_cert; - if (_security_db->get_hash(certificate_id, hash_cert) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_nistp256: Failed to get whole hash certificate"); - return -1; - } - loggers::get_instance().log_msg("security_services::sign_ecdsa_nistp256: hash_issuer: ", hash_cert); - OCTETSTRING os = p_hash + hash_cert; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::sign_ecdsa_nistp256: hash: ", os); - OCTETSTRING hashed_data; - hash_sha256(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - security_ecc k(ec_elliptic_curves::nist_p_256, pkey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashed_data, r_sig, s_sig) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_nistp256: Failed to sign payload"); - return -1; - } - Ieee1609Dot2BaseTypes::EccP256CurvePoint ep; - ep.x__only() = r_sig; - p_signature.ecdsaNistP256Signature() = Ieee1609Dot2BaseTypes::EcdsaP256Signature(ep, s_sig); - loggers::get_instance().log_msg("security_services::sign_ecdsa_nistp256: signature=", p_signature); - - return 0; -} - -int security_services::verify_sign_ecdsa_nistp256(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, - const std::string &p_certificate_id, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::verify_sign_ecdsa_nistp256:", p_hash); - loggers::get_instance().log(">>> security_services::verify_sign_ecdsa_nistp256: %s", p_certificate_id.c_str()); - - OCTETSTRING public_key_x; - OCTETSTRING public_key_y; - if (_security_db->get_public_keys(p_certificate_id, public_key_x, public_key_y) != 0) { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_nistp256 (%s): Failed to get public keys", p_certificate_id.c_str()); - return -1; - } - - // Generate the hash to be verified: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - OCTETSTRING issuer; // Hash (Signer identifier input) - if (_security_db->get_hash(p_certificate_id, issuer) != 0) { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_nistp256 (%s): Failed to get hash of the issuer certificate", - p_certificate_id.c_str()); - return -1; - } - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_nistp256: hash_issuer: ", issuer); - OCTETSTRING hash_data = p_hash + issuer; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_nistp256: hash: ", hash_data); - OCTETSTRING hash_to_be_verified; - hash_sha256(hash_data, hash_to_be_verified); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_nistp256: hash_to_be_verified: ", hash_to_be_verified); - - // Build the signature - OCTETSTRING signature; - if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_x__only)) { - signature = p_signature.ecdsaNistP256Signature().rSig().x__only() + p_signature.ecdsaNistP256Signature().sSig(); - } else if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - signature = p_signature.ecdsaNistP256Signature().rSig().compressed__y__0() + p_signature.ecdsaNistP256Signature().sSig(); - } else if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - signature = p_signature.ecdsaNistP256Signature().rSig().compressed__y__1() + p_signature.ecdsaNistP256Signature().sSig(); - } else if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - signature = p_signature.ecdsaNistP256Signature().rSig().uncompressedP256().x() + p_signature.ecdsaNistP256Signature().rSig().uncompressedP256().y() + - p_signature.ecdsaNistP256Signature().sSig(); - } else { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_nistp256 (%s): Invalid curve point", p_certificate_id.c_str()); - return -1; - } - security_ecc k(ec_elliptic_curves::nist_p_256, public_key_x, public_key_y); - if (k.sign_verif(hash_to_be_verified, signature) == 0) { - return 0; - } - - return -1; -} - -int security_services::sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::sign_ecdsa_brainpoolp256r1: ", p_hash); - - std::string certificate_id = p_params[params::certificate]; - loggers::get_instance().log("security_services::sign_ecdsa_brainpoolp256r1: encoded certificate_id = '%s'", certificate_id.c_str()); - OCTETSTRING pkey; - if (_security_db->get_private_key(certificate_id, pkey) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp256r1: Failed to get private key"); - return -1; - } - // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - OCTETSTRING hash_cert; - if (_security_db->get_hash(certificate_id, hash_cert) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp256r1: Failed to get whole hash certificate"); - return -1; - } - loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp256r1: hash_issuer: ", hash_cert); - OCTETSTRING os = p_hash + hash_cert; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp256r1: hash: ", os); - OCTETSTRING hashed_data; - hash_sha256(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, pkey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashed_data, r_sig, s_sig) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp256r1: Failed to sign payload"); - return -1; - } - Ieee1609Dot2BaseTypes::EccP256CurvePoint ep; - ep.x__only() = r_sig; - p_signature.ecdsaBrainpoolP256r1Signature() = Ieee1609Dot2BaseTypes::EcdsaP256Signature(ep, s_sig); - loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp256r1: signature=", p_signature); - - return 0; -} - -int security_services::verify_sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, - const std::string &p_certificate_id, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::verify_sign_ecdsa_brainpoolp256r1:", p_hash); - loggers::get_instance().log(">>> security_services::verify_sign_ecdsa_brainpoolp256r1: %s", p_certificate_id.c_str()); - - OCTETSTRING public_key_x; - OCTETSTRING public_key_y; - if (_security_db->get_public_keys(p_certificate_id, public_key_x, public_key_y) != 0) { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp256r1 (%s): Failed to get public keys", p_certificate_id.c_str()); - return -1; - } - - // Generate the hash to be verified: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - OCTETSTRING issuer; // Hash (Signer identifier input) - if (_security_db->get_hash(p_certificate_id, issuer) != 0) { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp256r1 (%s): Failed to get hash of the issuer certificate", - p_certificate_id.c_str()); - return -1; - } - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp256r1: hash_issuer: ", issuer); - OCTETSTRING hash_data = p_hash + issuer; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp256r1: hash: ", hash_data); - OCTETSTRING hash_to_be_verified; - hash_sha256(hash_data, hash_to_be_verified); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp256r1: hash_to_be_verified: ", hash_to_be_verified); - - // Build the signature - OCTETSTRING signature; - if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_x__only)) { - signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().x__only() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); - } else if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().compressed__y__0() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); - } else if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().compressed__y__1() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); - } else if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().uncompressedP256().x() + - p_signature.ecdsaBrainpoolP256r1Signature().rSig().uncompressedP256().y() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); - } else { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp256r1 (%s): Invalid curve point", p_certificate_id.c_str()); - return -1; - } - security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, public_key_x, public_key_y); - if (k.sign_verif(hash_to_be_verified, signature) == 0) { - return 0; - } - - return -1; -} - -int security_services::sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::sign_ecdsa_brainpoolp384r1: ", p_hash); - - std::string certificate_id = p_params[params::certificate]; - loggers::get_instance().log("security_services::sign_ecdsa_brainpoolp384r1: encoded certificate_id = '%s'", certificate_id.c_str()); - OCTETSTRING pkey; - if (_security_db->get_private_key(certificate_id, pkey) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp384r1: Failed to get private key"); - return -1; - } - // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - OCTETSTRING hash_cert; - if (_security_db->get_hash(certificate_id, hash_cert) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp384r1: Failed to get whole hash certificate"); - return -1; - } - loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp384r1: hash_issuer: ", hash_cert); - OCTETSTRING os = p_hash + hash_cert; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp384r1: hash: ", os); - OCTETSTRING hashed_data; - hash_sha384(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, pkey); - OCTETSTRING r_sig; - OCTETSTRING s_sig; - if (k.sign(hashed_data, r_sig, s_sig) != 0) { - loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp384r1: Failed to sign payload"); - return -1; - } - Ieee1609Dot2BaseTypes::EccP384CurvePoint ep; - ep.x__only() = r_sig; - p_signature.ecdsaBrainpoolP384r1Signature() = Ieee1609Dot2BaseTypes::EcdsaP384Signature(ep, s_sig); - loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp384r1: signature=", p_signature); - - return 0; -} - -int security_services::verify_sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, - const std::string &p_certificate_id, params &p_params) { - loggers::get_instance().log_msg(">>> security_services::verify_sign_ecdsa_brainpoolp384r1:", p_hash); - loggers::get_instance().log(">>> security_services::verify_sign_ecdsa_brainpoolp384r1: %s", p_certificate_id.c_str()); - - OCTETSTRING public_key_x; - OCTETSTRING public_key_y; - if (_security_db->get_public_keys(p_certificate_id, public_key_x, public_key_y) != 0) { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp384r1 (%s): Failed to get public keys", p_certificate_id.c_str()); - return -1; - } - - // Generate the hash to be verified: Hash ( Hash (Data input) || Hash (Signer identifier input) ) - OCTETSTRING issuer; // Hash (Signer identifier input) - if (_security_db->get_hash(p_certificate_id, issuer) != 0) { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp384r1 (%s): Failed to get hash of the issuer certificate", - p_certificate_id.c_str()); - return -1; - } - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp384r1: hash_issuer: ", issuer); - OCTETSTRING hash_data = p_hash + issuer; // Hash (Data input) || Hash (Signer identifier input) - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp384r1: hash: ", hash_data); - OCTETSTRING hash_to_be_verified; - hash_sha384(hash_data, hash_to_be_verified); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) - loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp384r1: hash_to_be_verified: ", hash_to_be_verified); - - // Build the signature - OCTETSTRING signature; - if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_x__only)) { - signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().x__only() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); - } else if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__0)) { - signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().compressed__y__0() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); - } else if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__1)) { - signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().compressed__y__1() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); - } else if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_uncompressedP384)) { - signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().uncompressedP384().x() + - p_signature.ecdsaBrainpoolP384r1Signature().rSig().uncompressedP384().y() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); - } else { - loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp384r1 (%s): Invalid curve point", p_certificate_id.c_str()); - return -1; - } - security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, public_key_x, public_key_y); - if (k.sign_verif(hash_to_be_verified, signature) == 0) { - return 0; - } - - return -1; -} - -int security_services::extract_verification_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y, - OCTETSTRING &p_public_comp_key, INTEGER &p_public_comp_key_mode) { - loggers::get_instance().log("security_services::extract_verification_keys"); - - if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaNistP256)) { - if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().compressed__y__0(); - security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_comp_key, ecc_compressed_mode::compressed_y_0); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - p_public_comp_key_mode = INTEGER(0); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().ischosen( - Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().compressed__y__1(); - security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_comp_key, ecc_compressed_mode::compressed_y_1); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - p_public_comp_key_mode = INTEGER(1); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().ischosen( - Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - security_ecc ecc(ec_elliptic_curves::nist_p_256, p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().x(), - p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().y()); - p_public_comp_key = ecc.public_key_compressed(); - p_public_comp_key_mode = INTEGER((int)ecc.public_key_compressed_mode()); - p_public_key_x = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().x(); - p_public_key_y = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().y(); - } else { - loggers::get_instance().error("security_services::extract_verification_keys: Unsupported VerificationKey"); - return -1; - } - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaBrainpoolP256r1)) { - if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().ischosen( - Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().compressed__y__0(); - security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_0); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - p_public_comp_key_mode = INTEGER(0); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().ischosen( - Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().compressed__y__1(); - security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_1); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - p_public_comp_key_mode = INTEGER(1); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().ischosen( - Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - p_public_key_x = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().uncompressedP256().x(); - p_public_key_y = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().uncompressedP256().y(); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaBrainpoolP384r1)) { - p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().compressed__y__0(); - security_ecc ecc(ec_elliptic_curves::brainpool_p_384_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_0); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - p_public_comp_key_mode = INTEGER(0); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().ischosen( - Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__1)) { - p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().compressed__y__1(); - security_ecc ecc(ec_elliptic_curves::brainpool_p_384_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_1); - p_public_key_x = ecc.public_key_x(); - p_public_key_y = ecc.public_key_y(); - p_public_comp_key_mode = INTEGER(1); - } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().ischosen( - Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_uncompressedP384)) { - p_public_key_x = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().uncompressedP384().x(); - p_public_key_y = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().uncompressedP384().y(); - } else { - loggers::get_instance().error("security_services::extract_verification_keys: Unsupported VerificationKey"); - return -1; - } - } else { - loggers::get_instance().error("security_services::extract_verification_keys: Unsupported VerificationKey"); - return -1; - } - - return 0; -} - -int security_services::extract_encryption_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y, - OCTETSTRING &p_public_enc_comp_key, INTEGER &p_public_enc_comp_key_mode) { - loggers::get_instance().log("security_services::extract_encryption_keys"); - - if (p_cert.toBeSigned().encryptionKey().ispresent()) { - const Ieee1609Dot2BaseTypes::PublicEncryptionKey &p = static_cast(p_cert.toBeSigned().encryptionKey()); - if (p.publicKey().ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesNistP256)) { - if (p.publicKey().eciesNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - p_public_enc_comp_key = p.publicKey().eciesNistP256().compressed__y__0(); - security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_0); - p_public_enc_key_x = ecc.public_key_x(); - p_public_enc_key_y = ecc.public_key_y(); - p_public_enc_comp_key_mode = INTEGER(0); - } else if (p.publicKey().eciesNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - const OCTETSTRING &p_public_enc_comp_key = p.publicKey().eciesNistP256().compressed__y__1(); - security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_1); - p_public_enc_key_x = ecc.public_key_x(); - p_public_enc_key_y = ecc.public_key_y(); - p_public_enc_comp_key_mode = INTEGER(1); - } else if (p.publicKey().eciesNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - p_public_enc_key_x = p.publicKey().eciesNistP256().uncompressedP256().x(); - p_public_enc_key_y = p.publicKey().eciesNistP256().uncompressedP256().y(); - } else { - loggers::get_instance().error("security_services::extract_encryption_keys: Unsupported EncryptionKey"); - return -1; - } - } else if (p.publicKey().ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesBrainpoolP256r1)) { - if (p.publicKey().eciesBrainpoolP256r1().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { - p_public_enc_comp_key = p.publicKey().eciesBrainpoolP256r1().compressed__y__0(); - security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_0); - p_public_enc_key_x = ecc.public_key_x(); - p_public_enc_key_y = ecc.public_key_y(); - p_public_enc_comp_key_mode = INTEGER(0); - } else if (p.publicKey().eciesBrainpoolP256r1().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { - p_public_enc_comp_key = p.publicKey().eciesBrainpoolP256r1().compressed__y__1(); - security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_1); - p_public_enc_key_x = ecc.public_key_x(); - p_public_enc_key_y = ecc.public_key_y(); - p_public_enc_comp_key_mode = INTEGER(1); - } else if (p.publicKey().eciesBrainpoolP256r1().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { - p_public_enc_key_x = p.publicKey().eciesBrainpoolP256r1().uncompressedP256().x(); - p_public_enc_key_y = p.publicKey().eciesBrainpoolP256r1().uncompressedP256().y(); - } else { - loggers::get_instance().error("security_services::extract_encryption_keys: Unsupported EncryptionKey"); - return -1; - } - } else { - loggers::get_instance().error("security_services::extract_encryption_keys: Unsupported EncryptionKey"); - return -1; - } - } else { - loggers::get_instance().warning("security_services::extract_encryption_keys: EncryptionKey omitted"); - p_public_enc_key_x = OCTETSTRING(0, nullptr); - p_public_enc_key_y = OCTETSTRING(0, nullptr); - p_public_enc_comp_key = OCTETSTRING(0, nullptr); - return 0; // Normal termination - } - - return 0; -} // End of method extract_encryption_keys - -int security_services::extract_and_store_certificate(const Ieee1609Dot2::CertificateBase &p_certificate, std::string &p_certificate_id) { - loggers::get_instance().log_msg(">>> security_services::extract_and_store_certificate: ", p_certificate); - - // Encode certificate - etsi_ts103097_certificate_codec codec; - OCTETSTRING enc_cert; - codec.encode(p_certificate, enc_cert); - if (enc_cert.lengthof() == 0) { - loggers::get_instance().warning("security_services::extract_and_store_certificate: Failed to encode certificate"); - return -1; - } - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Encoded certificate=", enc_cert); - OCTETSTRING hash_cert_sha_256; - hash_sha256(enc_cert, hash_cert_sha_256); - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: hash_cert_sha_256= ", hash_cert_sha_256); - int result = -1; - if (p_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha256AndDigest)) { - // Calculate the hash according to the hashId - OCTETSTRING hash_cert(hash_cert_sha_256); - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: hash_cert= ", hash_cert); - const OCTETSTRING hashed_id8 = substr(hash_cert, hash_cert.lengthof() - 8, 8); - // Retrieve the certificate identifier from digest - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Retrieve the certificate identifier from digest: ", hashed_id8); - result = _security_db.get()->get_certificate_id(hashed_id8, p_certificate_id); - if (result == -1) { // Not found in current DB - if (_security_cache.get()->get_certificate_id(hashed_id8, p_certificate_id) == -1) { // Not found in TS cache - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Store new certificate in cache: ", p_certificate); - // const std::vector v(static_cast(hashed_id8), static_cast(hashed_id8) + - // hashed_id8.lengthof()); p_certificate_id = converter::get_instance().bytes_to_hexa(v); - p_certificate_id = std::string(static_cast(hex2str(oct2hex(hashed_id8)))); - // Add it into the cache - OCTETSTRING public_key_x, public_key_y, public_comp_key; - INTEGER public_comp_key_mode; - if (extract_verification_keys(p_certificate, public_key_x, public_key_y, public_comp_key, public_comp_key_mode) == -1) { - loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); - return -1; - } - // Add encryption keys - OCTETSTRING public_enc_key_x, public_enc_key_y, public_enc_comp_key; - INTEGER public_enc_comp_key_mode; - if (extract_encryption_keys(p_certificate, public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode) == -1) { - loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); - return -1; - } - // And store it into the cache - _security_cache.get()->store_certificate(CHARSTRING(p_certificate_id.c_str()), enc_cert, int2oct(0, 32), // No way to get the private key here - public_key_x, public_key_y, public_comp_key, public_comp_key_mode, hash_cert, hash_cert_sha_256, hashed_id8, - p_certificate.issuer().sha256AndDigest(), OCTETSTRING(0, nullptr), // Encryption private not used - public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode); - } - } - } else if (p_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha384AndDigest)) { - // Calculate the hash according to the hashId - OCTETSTRING hash_cert; - hash_sha384(enc_cert, hash_cert); - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: hash_cert= ", hash_cert); - const OCTETSTRING hashed_id8 = substr(hash_cert, hash_cert.lengthof() - 8, 8); - // Retrieve the certificate identifier from digest - loggers::get_instance().log("security_services::extract_and_store_certificate: Retrieve the certificate identifier from digest"); - result = _security_db.get()->get_certificate_id(hashed_id8, p_certificate_id); - if (result == -1) { - if (_security_cache.get()->get_certificate_id(hashed_id8, p_certificate_id) == -1) { - loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Store new certificate in cache: ", p_certificate); - // const std::vector v(static_cast(hashed_id8), static_cast(hashed_id8) + - // hashed_id8.lengthof()); p_certificate_id = converter::get_instance().bytes_to_hexa(v); - p_certificate_id = std::string(static_cast(hex2str(oct2hex(hashed_id8)))); - // Add it into the cache - OCTETSTRING public_key_x, public_key_y, public_comp_key; - INTEGER public_comp_key_mode; - if (extract_verification_keys(p_certificate, public_key_x, public_key_y, public_comp_key, public_comp_key_mode) == -1) { - loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); - return -1; - } - // Add encryption keys - OCTETSTRING public_enc_key_x, public_enc_key_y, public_enc_comp_key; - INTEGER public_enc_comp_key_mode; - if (extract_encryption_keys(p_certificate, public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode) == -1) { - loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); - return -1; - } - // And store it into the cache - _security_cache.get()->store_certificate(CHARSTRING(p_certificate_id.c_str()), enc_cert, int2oct(0, 48), // No way to get the private key here - public_key_x, public_key_y, public_comp_key, public_comp_key_mode, hash_cert, hash_cert_sha_256, hashed_id8, - p_certificate.issuer().sha384AndDigest(), OCTETSTRING(0, nullptr), // Encryption private not used - public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode); - } - } - } else { - loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported issuer"); - return -1; - } - - return 0; -} // End of method extract_and_store_certificate - -int security_services::read_certificate(const CHARSTRING &p_certificate_id, OCTETSTRING &p_certificate) const { - return _security_db.get()->get_certificate(std::string(static_cast(p_certificate_id)), p_certificate); -} - -int security_services::read_certificate_digest(const CHARSTRING &p_certificate_id, OCTETSTRING &p_digest) const { - return _security_db.get()->get_hashed_id(std::string(static_cast(p_certificate_id)), p_digest); -} - -int security_services::read_certificate_hash(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const { - return _security_db.get()->get_hash(std::string(static_cast(p_certificate_id)), p_hash); -} - -int security_services::read_certificate_hash_sha_256(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const { - return _security_db.get()->get_hash_sha_256(std::string(static_cast(p_certificate_id)), p_hash); -} - -int security_services::read_certificate_from_digest(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const { - std::string certificate_id; - if (_security_db.get()->get_certificate_id(p_digest, certificate_id) != -1) { - p_certificate_id = CHARSTRING(certificate_id.c_str()); - return 0; - } - return -1; -} - -int security_services::read_certificate_from_hashed_id3(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const { - std::string certificate_id; - if (_security_db.get()->get_certificate_hashed_id3(p_digest, certificate_id) != -1) { - p_certificate_id = CHARSTRING(certificate_id.c_str()); - return 0; - } - return -1; -} - -int security_services::read_private_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_key) const { - return _security_db.get()->get_private_key(std::string(static_cast(p_certificate_id)), p_private_key); -} - -int security_services::read_private_enc_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_enc_key) const { - return _security_db.get()->get_private_enc_key(std::string(static_cast(p_certificate_id)), p_private_enc_key); -} +#include + +#include + +#include "security_services.hh" + +using namespace std; // Required for isnan() +#include "etsi_ts103097_certificate_codec.hh" +#include "etsi_ts103097_data_codec.hh" +#include "etsi_ts103097_tobesigned_data_codec.hh" + +#include "security_ecc.hh" +#include "sha256.hh" +#include "sha384.hh" + +#include "base_time.hh" + +#include "params.hh" + +#include "loggers.hh" + +#include "converter.hh" + +security_services *security_services::instance = nullptr; + +security_services::security_services() + : _setup_done{false}, _ec_keys_enc(nullptr), _security_cache(new security_cache), _security_db(nullptr), _last_generation_time(0), + _unknown_certificate(0, nullptr), _requested_certificate(), _latitude(0), _longitude(0), _elevation(0), _geospacial() { + loggers::get_instance().log(">>> security_services::security_services"); + + //_geospacial.load_countries_map("/home/yann/dev/TTF0002_Its/ne-countries-50m.json"); // FIXME Use parameter + +} // End of ctor + +int security_services::setup(params &p_params) { // FIXME Rename this method + loggers::get_instance().log(">>> security_services::setup"); + _params = p_params; + _params.log(); + + if (_setup_done) { + loggers::get_instance().warning("security_services::setup: Already done"); + return 0; + } + + // Build the certificate caching + try { + _security_db.reset(new security_db(_params[params::sec_db_path])); + if (_security_db.get() == nullptr) { // Memory allocation issue + loggers::get_instance().warning("security_services::setup: _security_db pointer is NULL"); + return -1; + } + _setup_done = true; + } catch (...) { + loggers::get_instance().error("security_services::setup: Filesystem access error, terminate test suite on TTCN-3 error. Please check user name and paths " + "in the test suite configuration file."); + return -1; + } + + // Initialise encryption mechanism + params::const_iterator it = _params.find(params::cypher); + if (it == _params.cend()) { + _ec_keys_enc.reset(new security_ecc(ec_elliptic_curves::nist_p_256)); + _params.insert(std::pair(params::cypher, std::string("NISTP-256"))); + p_params.insert(std::pair(params::cypher, std::string("NISTP-256"))); + } else if (it->second.compare("NISTP-256")) { + _ec_keys_enc.reset(new security_ecc(ec_elliptic_curves::nist_p_256)); + } else if (it->second.compare("BP-256")) { + _ec_keys_enc.reset(new security_ecc(ec_elliptic_curves::brainpool_p_256_r1)); + } else { + loggers::get_instance().warning("security_services::setup: Failed to encode ToBeSignedData"); + return -1; + } + + return 0; +} + +int security_services::store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, + const OCTETSTRING &p_public_key_x, const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_comp_key, + const INTEGER &p_public_comp_key_mode, const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, + const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, const OCTETSTRING &p_private_enc_key, + const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, + const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_key_compressed_mode) { + loggers::get_instance().log_msg(">>> security_services::store_certificate: ", p_cert_id); + + // Sanity checks + if (_security_db.get() == nullptr) { // Setup not called + loggers::get_instance().warning("security_services::store_certificate: Not initialised"); + return -1; + } + return _security_db.get()->store_certificate(p_cert_id, p_cert, p_private_key, p_public_key_x, p_public_key_y, p_public_comp_key, p_public_comp_key_mode, + p_hash, p_hash_sha_256, p_hashid8, p_issuer, p_private_enc_key, p_public_enc_key_x, p_public_enc_key_y, + p_public_enc_compressed_key, p_public_enc_key_compressed_mode); +} + +int security_services::verify_and_extract_gn_payload(const OCTETSTRING &p_secured_gn_payload, const bool p_verify, + Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, OCTETSTRING &p_unsecured_gn_payload, + params &p_params) { + loggers::get_instance().log_msg(">>> security_services::verify_and_extract_gn_payload: ", p_secured_gn_payload); + + // Sanity checks + if (p_secured_gn_payload.lengthof() == 0) { + return -1; + } + + // Decode the secured message (OER encoding) + etsi_ts103097_data_codec codec; + codec.decode(p_secured_gn_payload, p_ieee_1609dot2_data, &p_params); + // Sanity checks + if (!p_ieee_1609dot2_data.is_bound()) { + loggers::get_instance().warning("security_services::verify_and_extract_gn_payload: Unbound value, discard it"); + return -1; + } + if (p_verify && ((unsigned int)(int)p_ieee_1609dot2_data.protocolVersion() != security_services::ProtocolVersion)) { + loggers::get_instance().warning("security_services::verify_and_extract_gn_payload: Wrong version protocol, discard it"); + return -1; + } + + return process_ieee_1609_dot2_content(p_ieee_1609dot2_data.content(), p_verify, p_unsecured_gn_payload, p_params); +} // End of method verify_and_extract_gn_payload + +int security_services::process_ieee_1609_dot2_content(const Ieee1609Dot2::Ieee1609Dot2Content &p_ieee_1609_dot2_content, const bool p_verify, + OCTETSTRING &p_unsecured_payload, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::process_ieee_1609_dot2_content: ", p_ieee_1609_dot2_content); + + if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_unsecuredData)) { // Unsecured packet, End of recursivity + p_unsecured_payload = p_ieee_1609_dot2_content.unsecuredData(); + } else if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_signedData)) { + const Ieee1609Dot2::SignedData &signedData = p_ieee_1609_dot2_content.signedData(); + if (process_ieee_1609_dot2_signed_data(signedData, p_verify, p_unsecured_payload, p_params) != 0) { + if (p_verify) { + return -1; + } + } + } else if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_encryptedData)) { + const Ieee1609Dot2::EncryptedData &encrypted_data = p_ieee_1609_dot2_content.encryptedData(); + OCTETSTRING signed_payload; + if (process_ieee_1609_dot2_encrypted_data(encrypted_data, p_verify, signed_payload, p_params) != 0) { + return -1; + } + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_content: Decrypted payload: ", signed_payload); + Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data; // TODO Check if it could be reused + if (verify_and_extract_gn_payload(signed_payload, p_verify, ieee_1609dot2_data, p_unsecured_payload, p_params) != 0) { + if (p_verify) { + return -1; + } + } + } else if (p_ieee_1609_dot2_content.ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_signedCertificateRequest)) { + // Reset certificate timer + loggers::get_instance().log("security_services::process_ieee_1609_dot2_content: Set Certificate re-transmission flag and reset timer"); + _last_generation_time = 0; + return 0; + } else { // Shall never be reached + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_content: Undefined IEEE 1609.2 Content, discard it"); + if (p_verify) { + return -1; + } + } + + loggers::get_instance().log_msg("<<< security_services::process_ieee_1609_dot2_content: ", p_unsecured_payload); + return 0; +} // End of method process_ieee_1609_dot2_content + +int security_services::process_ieee_1609_dot2_signed_data(const Ieee1609Dot2::SignedData &p_signed_data, const bool p_verify, OCTETSTRING &p_unsecured_payload, + params &p_params) { + loggers::get_instance().log_msg(">>> security_services::process_ieee_1609_dot2_signed_data: ", p_signed_data); + + // Check the headerInfo content + const Ieee1609Dot2::HeaderInfo &header_info = p_signed_data.tbsData().headerInfo(); + p_params[params::its_aid] = std::to_string(header_info.psid().get_long_long_val()); + if (!header_info.generationTime().is_present()) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: HeaderInfo::GenerationTime field is missing"); + if (p_verify) { + return -1; + } + } else { + const OPTIONAL &v = dynamic_cast &>(header_info.generationTime()); // in microsecond + unsigned long long gt = ((INTEGER &)(*v.get_opt_value())).get_long_long_val(); + // Get current time timestamp + unsigned long long us = base_time::get_instance().get_its_current_time_us(); // in microsecond + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: generation time check %ld / %ld, delta = %f", gt, us, + abs((double)gt - (double)us)); + if (abs((double)gt - (double)us) >= 5000000.0) { // TODO Use a params for generation_time_epsilon, 5s differences + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Invalid generation time, discard it"); + if (p_verify) { + return -1; + } + } + } + + // Check p2pcdLearningRequest keys if present + if (header_info.p2pcdLearningRequest().is_present()) { + loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: p2pcdLearningRequest not supported yet"); + // TODO Not supported by C-ITS Protocol + } + + // Check missingCrlIdentifier keys if present + if (header_info.missingCrlIdentifier().is_present()) { + loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: missingCrlIdentifier not supported yet"); + // TODO Not supported by C-ITS Protocol + } + + // Check encryption keys if present + if (header_info.encryptionKey().is_present()) { + loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: encryptionKey not supported yet"); + // TODO Not supported by C-ITS Protocol + } + + // Check request certificate + if (header_info.inlineP2pcdRequest().is_present()) { + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: inlineP2pcdRequest: ", header_info.inlineP2pcdRequest()); + const Ieee1609Dot2BaseTypes::SequenceOfHashedId3 &s = + static_cast(*header_info.inlineP2pcdRequest().get_opt_value()); + _requested_certificate.clear(); + for (int i = 0; i < s.lengthof(); i++) { + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: Add requested certificate= ", s[i]); + _requested_certificate.push_back(s[i]); + } // End of 'for' statement + } + + // Check requested certificate + if (header_info.requestedCertificate().is_present()) { + loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: requestedCertificate not supported yet"); + // TODO Not supported by C-ITS Protocol + } + + // Check and extract unsecured payload + if (p_signed_data.tbsData().payload().data().is_present()) { + // Check protocol version + const OPTIONAL &v = + dynamic_cast &>(p_signed_data.tbsData().payload().data()); + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: SignedDataPayload.data=", v); + const Ieee1609Dot2::Ieee1609Dot2Data &ieee_1609dot2_data = static_cast(*v.get_opt_value()); + if (p_verify && ((unsigned int)(int)ieee_1609dot2_data.protocolVersion() != security_services::ProtocolVersion)) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Wrong version protocol, discard it"); + if (p_verify) { + return -1; + } + } + if (process_ieee_1609_dot2_content(ieee_1609dot2_data.content(), p_verify, p_unsecured_payload, p_params) != 0) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to process SignedData, discard it"); + if (p_verify) { + return -1; + } + } + } else if (p_signed_data.tbsData().payload().extDataHash().is_present()) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unsupported extDataHash, discard it"); + if (p_verify) { + return -1; + } + } else { // Shall not be reached + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unsupported SignedDataPayload, discard it"); + return -1; + } + + // Encode the ToBeSignedData + etsi_ts103097_tobesigned_data_codec tbs_data_codec; + OCTETSTRING os; + tbs_data_codec.encode(p_signed_data.tbsData(), os); + if (os.lengthof() == 0) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to encode ToBeSignedData"); + return -1; + } + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: encoded tbs_data=", os); + // Calculate the hash according to the hashId + OCTETSTRING hashed_data; + if (p_signed_data.hashId() == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { + hash_sha256(os, hashed_data); + } else { + hash_sha384(os, hashed_data); + } + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: hashed_data=", hashed_data); + // Retrieve certificate identifier + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: signer=", p_signed_data.signer()); + std::string certificate_id; + int result = -1; + if (p_signed_data.signer().ischosen(Ieee1609Dot2::SignerIdentifier::ALT_digest)) { + // Retrieve the certificate identifier from digest + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: Retrieve the certificate identifier from digest"); + result = _security_db.get()->get_certificate_id(p_signed_data.signer().digest(), certificate_id); + if (result == -1) { + // Check in the cache + if (_security_cache.get()->get_certificate_id(p_signed_data.signer().digest(), certificate_id) == -1) { + // Unknown certificate, request it + const OCTETSTRING &os = p_signed_data.signer().digest(); + _unknown_certificate = OCTETSTRING(3, static_cast(os) + os.lengthof() - 3); + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unknown certificate, request it"); + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: HashedId3: ", _unknown_certificate); + } + // Reset certificate timer + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: Set Certificate re-transmission flag and reset timer"); + _last_generation_time = 0; + + return -1; + } + } else if (p_signed_data.signer().ischosen(Ieee1609Dot2::SignerIdentifier::ALT_certificate) && (p_signed_data.signer().certificate().size_of() != 0)) { + // Extract the certificates + std::vector certificate_ids; + for (int i = 0; i < p_signed_data.signer().certificate().size_of(); i++) { + Ieee1609Dot2::CertificateBase cert = p_signed_data.signer().certificate()[i]; + // Retrieve ssps + OPTIONAL &v = cert.toBeSigned().appPermissions(); + if (v.is_present()) { + Ieee1609Dot2BaseTypes::SequenceOfPsidSsp psid_ssps = static_cast(*v.get_opt_value()); + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: psid_ssps size: %d", psid_ssps.lengthof()); + for (int i = 0; i < psid_ssps.lengthof(); i++) { + const Ieee1609Dot2BaseTypes::PsidSsp &psid_ssp = psid_ssps[i]; + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: Processing psid_ssp ", psid_ssp); + const OPTIONAL &s = psid_ssp.ssp(); + if (s.is_present()) { + const Ieee1609Dot2BaseTypes::ServiceSpecificPermissions &ssp = static_cast(s); + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: Processing ssp ", ssp); + params::const_iterator it = p_params.find(std::to_string(psid_ssp.psid())); + if (it == p_params.cend()) { + OCTETSTRING os; + if (ssp.ischosen(Ieee1609Dot2BaseTypes::ServiceSpecificPermissions::ALT_opaque)) { + os = ssp.opaque(); + } else { + os = ssp.bitmapSsp(); + } + p_params[params::ssp] = std::string(static_cast(oct2str(os))); + } + } + } // End of 'for' statement + } + + std::string certificate_id; + if (extract_and_store_certificate(cert, certificate_id) != 0) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to store certificate"); + if (p_verify) { + return -1; + } + } + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: certificate_id: '%s'", certificate_id.c_str()); + certificate_ids.push_back(certificate_id); + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: certificate_ids size: %d", certificate_ids.size()); + } // End of 'for' statement + certificate_id = certificate_ids[0]; + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: After extract_and_store_certificate, certificate_id: '%s'", + certificate_id.c_str()); + } else { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Unsupported SignerIdentifier"); + return -1; + } + loggers::get_instance().log("security_services::process_ieee_1609_dot2_signed_data: certificate id = '%s'", certificate_id.c_str()); + // Verify the signature of the ToBeSignedData + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_signed_data: signature=", p_signed_data.signature__()); + result = -1; + if (p_signed_data.signature__().ischosen(Ieee1609Dot2BaseTypes::Signature::ALT_ecdsaNistP256Signature)) { + result = verify_sign_ecdsa_nistp256(hashed_data, p_signed_data.signature__(), certificate_id, p_params); + } else if (p_signed_data.signature__().ischosen(Ieee1609Dot2BaseTypes::Signature::ALT_ecdsaBrainpoolP256r1Signature)) { + result = verify_sign_ecdsa_brainpoolp256r1(hashed_data, p_signed_data.signature__(), certificate_id, p_params); + } else if (p_signed_data.signature__().ischosen(Ieee1609Dot2BaseTypes::Signature::ALT_ecdsaBrainpoolP384r1Signature)) { + result = verify_sign_ecdsa_brainpoolp384r1(hashed_data, p_signed_data.signature__(), certificate_id, p_params); + } else { + // TODO + loggers::get_instance().error("security_services::process_ieee_1609_dot2_signed_data: TODO"); + } + if (result != 0) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_signed_data: Failed to verify signature"); + return -1; + } + + loggers::get_instance().log_msg("<<< security_services::process_ieee_1609_dot2_signed_data: ", p_unsecured_payload); + return 0; +} // End of method process_ieee_1609_dot2_signed_data + +int security_services::process_ieee_1609_dot2_encrypted_data(const Ieee1609Dot2::EncryptedData &p_encrypted_data, const bool p_verify, + OCTETSTRING &p_unsecured_payload, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::process_ieee_1609_dot2_encrypted_data: ", p_encrypted_data); + + // 1. Retrieve the RecipientId + const Ieee1609Dot2::RecipientInfo & r = p_encrypted_data.recipients()[0]; // TODO Add multiple support of recipients + const Ieee1609Dot2BaseTypes::EciesP256EncryptedKey *ecies = nullptr; // TODO Use smart pointer + const OCTETSTRING * recipient_id = nullptr; // TODO Use smart pointer + if (r.ischosen(Ieee1609Dot2::RecipientInfo::ALT_certRecipInfo)) { + recipient_id = &r.certRecipInfo().recipientId(); + if (r.certRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesNistP256)) { + ecies = &r.certRecipInfo().encKey().eciesNistP256(); + } else if (r.certRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesBrainpoolP256r1)) { + ecies = &r.certRecipInfo().encKey().eciesBrainpoolP256r1(); + } else { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported encryption algorithm"); + return -1; + } + } else if (r.ischosen(Ieee1609Dot2::RecipientInfo::ALT_signedDataRecipInfo)) { + recipient_id = &r.signedDataRecipInfo().recipientId(); + if (r.signedDataRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesNistP256)) { + ecies = &r.signedDataRecipInfo().encKey().eciesNistP256(); + } else if (r.signedDataRecipInfo().encKey().ischosen(Ieee1609Dot2::EncryptedDataEncryptionKey::ALT_eciesBrainpoolP256r1)) { + ecies = &r.signedDataRecipInfo().encKey().eciesBrainpoolP256r1(); + } else { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported encryption algorithm"); + return -1; + } + } else { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported RecipientInfo variant"); + return -1; + } + if (!p_encrypted_data.ciphertext().ischosen(Ieee1609Dot2::SymmetricCiphertext::ALT_aes128ccm)) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unsupported AES 128 algorithm"); + return -1; + } + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: RecipientId= ", *recipient_id); + + // 2. Retrieve the certificate if present + std::string certificate_id; + OCTETSTRING p_enc_key; // The private encryption key + if (_security_db.get()->get_certificate_id(*recipient_id, certificate_id) == -1) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Unknown certificate"); + // Check if RecipientId is the hashed_id8 of the symetric AES keys + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: AES Symmetric Keys= ", ecies->c()); + OCTETSTRING hashed_data; + hash_sha256(ecies->c(), hashed_data); + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: Hash (AES Symmetric Keys)= ", hashed_data); + if (substr(hashed_data, hashed_data.lengthof() - 8, 8) != *recipient_id) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: RecipientId does not match HashedId8 of the symmetric key"); + return -1; + } else { + if (_security_db.get()->get_private_enc_key(p_params[params::certificate], p_enc_key) == -1) { + loggers::get_instance().warning( + "security_services::process_ieee_1609_dot2_encrypted_data: Failed to retrieve private encryption key for certificate %s", + p_params[params::certificate].c_str()); + return -1; + } + } + } else { + if (_security_db.get()->get_private_enc_key(certificate_id, p_enc_key) == -1) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to retrieve private encryption key"); + return -1; + } + } + + // 3. Generate the shared secret value based on recipient's public ephemeral keys will be required + 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, 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)) { + 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)) { + 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; + } + if (result == -1) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to generate shared secret"); + return -1; + } + // 4. Decrypt the message + OCTETSTRING enc_message(p_encrypted_data.ciphertext().aes128ccm().ccmCiphertext().lengthof() - ec.tag().lengthof(), + static_cast(p_encrypted_data.ciphertext().aes128ccm().ccmCiphertext())); + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: enc_message: ", enc_message); + OCTETSTRING tag(ec.tag().lengthof(), enc_message.lengthof() + static_cast(p_encrypted_data.ciphertext().aes128ccm().ccmCiphertext())); + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: tag: ", tag); + if (ec.decrypt(tag, enc_message, p_unsecured_payload) == -1) { + loggers::get_instance().warning("security_services::process_ieee_1609_dot2_encrypted_data: Failed to generate shared secret"); + return -1; + } + loggers::get_instance().log_msg("security_services::process_ieee_1609_dot2_encrypted_data: ", p_unsecured_payload); + + return 0; +} // End of method process_ieee_1609_dot2_encrypted_data + +int security_services::secure_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_secured_gn_payload, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::secure_gn_payload: ", p_unsecured_gn_payload); + p_params.log(); + + OCTETSTRING signed_payload; + if (sign_payload(p_unsecured_gn_payload, signed_payload, p_params) != 0) { + p_secured_gn_payload = p_unsecured_gn_payload; + loggers::get_instance().warning("security_services::secure_gn_payload: Failed to signed payload"); + return -1; + } + + if (_params[params::encrypted_mode].compare("1") == 0) { + if (encrypt_gn_payload(signed_payload, p_secured_gn_payload, p_params) != 0) { + p_secured_gn_payload = signed_payload; + loggers::get_instance().warning("security_services::secure_gn_payload: Failed to encrypt payload"); + return -1; + } + } else { // No encryption required + loggers::get_instance().log("security_services::secure_gn_payload: Encryption mode not set"); + p_secured_gn_payload = signed_payload; + } + + return 0; +} + +int security_services::sign_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_signed_gn_payload, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::sign_payload: ", p_unsecured_gn_payload); + + // Set unsecured data + Ieee1609Dot2::Ieee1609Dot2Content unsecured_data_content; + unsecured_data_content.unsecuredData() = p_unsecured_gn_payload; + Ieee1609Dot2::Ieee1609Dot2Data unsecured_data(ProtocolVersion, unsecured_data_content); + // Set hash algorithm + Ieee1609Dot2BaseTypes::HashAlgorithm hashId(Ieee1609Dot2BaseTypes::HashAlgorithm::sha256); + if (p_params[params::hash].compare("SHA-384") == 0) { + hashId = Ieee1609Dot2BaseTypes::HashAlgorithm::sha384; + } + // Set SignedDataPayload + Ieee1609Dot2::SignedDataPayload payload; + payload.data() = unsecured_data; + payload.extDataHash().set_to_omit(); + Ieee1609Dot2::HeaderInfo header_info; + // Set secured field according to the payload! + header_info.psid() = converter::get_instance().string_to_int(p_params[params::its_aid]); + header_info.expiryTime().set_to_omit(); + if (p_params[params::its_aid].compare("37") == 0) { // Only used by AtsRSUSimulator to add location header + // Mandatory for DENM payload + OPTIONAL location(Ieee1609Dot2BaseTypes::ThreeDLocation(_latitude, _longitude, _elevation)); + header_info.generationLocation() = location; + loggers::get_instance().log_msg("security_services::sign_payload: generationLocation: ", header_info.generationLocation()); + } else { + header_info.generationLocation().set_to_omit(); + } + header_info.p2pcdLearningRequest().set_to_omit(); + header_info.missingCrlIdentifier().set_to_omit(); + if (_params[params::encrypted_mode].compare("1") == 0) { + // TODO Set the encrytion key. Not supported yet, need to clarify mechanism, see IEEE Std 1609.2-20XX Clause 6.3.9 HeaderInfo + header_info.encryptionKey().set_to_omit(); + } else { + header_info.encryptionKey().set_to_omit(); + } + params::const_iterator it = p_params.find(params::payload_type); + if (it != p_params.cend()) { + loggers::get_instance().log("security_services::sign_payload: Payload type: %s", it->second.c_str()); + if (it->second.compare("1") == 0) { // DENM + OPTIONAL location(Ieee1609Dot2BaseTypes::ThreeDLocation(_latitude, _longitude, _elevation)); + loggers::get_instance().log_msg("security_services::sign_payload: generationLocation: ", location); + header_info.generationLocation() = location; + loggers::get_instance().log_msg("security_services::sign_payload: generationLocation: ", header_info.generationLocation()); + } else if (it->second.compare("2") == 0) { // CAM + // Noting to do + } else { + // Noting to do + } + } else { // Process it as a GeoNetworking payload + loggers::get_instance().log("security_services::sign_payload: Payload type not set"); + // Noting to do + } + unsigned long long us = base_time::get_instance().get_its_current_time_us(); + loggers::get_instance().log("security_services::sign_payload: HeaderInfo timestamp: %ld", us); + INTEGER i; + i.set_long_long_val(us); + header_info.generationTime() = OPTIONAL(i); + loggers::get_instance().log("security_services::sign_payload: Final HeaderInfo timestamp: %ld", us); + // Check if a certificate shall be requested + if (_unknown_certificate.lengthof() == 3) { // HashedId3 of a requested certificate + Ieee1609Dot2BaseTypes::SequenceOfHashedId3 s; + s[0] = _unknown_certificate; + header_info.inlineP2pcdRequest() = OPTIONAL(s); + _unknown_certificate = OCTETSTRING(0, nullptr); + } else { + header_info.inlineP2pcdRequest().set_to_omit(); + } + if (_requested_certificate.size() != 0) { + Ieee1609Dot2::CertificateBase c; + const Ieee1609Dot2BaseTypes::HashedId3 &hashed_id3 = _requested_certificate[0]; + _security_db->get_certificate(hashed_id3, c); + header_info.requestedCertificate() = OPTIONAL(c); + } else { + header_info.requestedCertificate().set_to_omit(); + } + + Ieee1609Dot2::ToBeSignedData tbs_data; + tbs_data.payload() = payload; + tbs_data.headerInfo() = header_info; + loggers::get_instance().log_msg("security_services::sign_payload: tbs_data=", tbs_data); + // Sign the ToBeSignedData data structure + Ieee1609Dot2BaseTypes::Signature signature; + if (sign_tbs_data(tbs_data, hashId, signature, p_params) != 0) { + loggers::get_instance().warning("security_services::sign_payload: Failed to secure payload"); + return -1; + } + Ieee1609Dot2::SignerIdentifier signer; + loggers::get_instance().log("security_services::sign_payload: us = %ld - _last_generation_time = %ld - us - _last_generation_time = %ld", us, + _last_generation_time, us - _last_generation_time); + std::string certificate_id = p_params[params::certificate]; + loggers::get_instance().log("security_services::sign_payload: certificate_id = %s", certificate_id.c_str()); + if ((unsigned int)(us - _last_generation_time) >= 1000000 * 0.95) { // Need to add certificate every 1s + loggers::get_instance().log("security_services::sign_payload: Need to add certificate"); + Ieee1609Dot2::CertificateBase cert; + if (_security_db->get_certificate(certificate_id, cert) != 0) { + loggers::get_instance().warning("security_services:sign_payload: Failed to secure payload"); + return -1; + } + loggers::get_instance().log("security_services::sign_payload: cert= ", cert); + Ieee1609Dot2::SequenceOfCertificate sequenceOfCertificate; + sequenceOfCertificate[0] = cert; + signer.certificate() = sequenceOfCertificate; + // Reset send certificate timer + _last_generation_time = us; + loggers::get_instance().log("security_services::sign_payload: Reset send certificate timer, signer= ", signer); + } else { + loggers::get_instance().log("security_services::sign_payload: Add digest"); + OCTETSTRING digest; + if (_security_db->get_hashed_id(certificate_id, digest) != 0) { + loggers::get_instance().warning("security_services::sign_payload: Failed to secure payload"); + return -1; + } + signer.digest() = digest; + } + Ieee1609Dot2::SignedData signed_data(hashId, tbs_data, signer, signature); + loggers::get_instance().log_msg("security_services::sign_payload: signed_data=", signed_data); + Ieee1609Dot2::Ieee1609Dot2Content ieee_dot2_content; + ieee_dot2_content.signedData() = signed_data; + Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data(security_services::ProtocolVersion, ieee_dot2_content); + loggers::get_instance().log_msg("security_services::sign_payload: ieee_1609dot2_data=", ieee_1609dot2_data); + etsi_ts103097_data_codec codec; + codec.encode(ieee_1609dot2_data, p_signed_gn_payload); + if (!p_signed_gn_payload.is_bound()) { + loggers::get_instance().warning("security_services::sign_payload: Failed to encode Ieee1609Dot2Data"); + return -1; + } + + return 0; +} + +int security_services::encrypt_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_enc_gn_payload, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::encrypt_gn_payload: ", p_unsecured_gn_payload); + + // Sanity checks + if (_ec_keys_enc.get() == nullptr) { + loggers::get_instance().warning("security_services::encrypt_gn_payload: Encryption not initialised"); + return -1; + } + params::const_iterator it = p_params.find(params::peer_certificate); + if (it == p_params.cend()) { + loggers::get_instance().warning("security_services::encrypt_gn_payload: Encryption impossible without a peer_certificte indication in parameters"); + return -1; + } + std::string certificate_id = it->second; + loggers::get_instance().log("security_services::encrypt_gn_payload: Peer CertificateId=%s", certificate_id.c_str()); + + // 1. Retrieve recipient's public keys + OCTETSTRING r_public_key_x; + OCTETSTRING r_public_key_y; + if (_security_db.get()->get_public_enc_keys(certificate_id, r_public_key_x, r_public_key_y) == -1) { + loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to retrieve recipient's public keys"); + // TODO Setup request certificate mechanism + return -1; + } + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: r_public_key_x=", r_public_key_x); + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: r_public_key_y=", r_public_key_y); + + // 2. Generate new Private/Public ephemeral keys + if (_ec_keys_enc.get()->generate() == -1) { + loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to generate ephemeral keys"); + return -1; + } + + // 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, OCTETSTRING(0, nullptr)) == -1) { + loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to generate and derive secret key"); + return -1; + } + + // 4. Buil curve data structure in canonical form + Ieee1609Dot2BaseTypes::EccP256CurvePoint eccP256CurvePoint; + if (_ec_keys_enc.get()->public_key_compressed_mode() == ecc_compressed_mode::compressed_y_0) { + eccP256CurvePoint.compressed__y__0() = _ec_keys_enc.get()->public_key_compressed(); + } else if (_ec_keys_enc.get()->public_key_compressed_mode() == ecc_compressed_mode::compressed_y_1) { + eccP256CurvePoint.compressed__y__1() = _ec_keys_enc.get()->public_key_compressed(); + } else { + eccP256CurvePoint.uncompressedP256().x() = _ec_keys_enc.get()->public_key_x(); + eccP256CurvePoint.uncompressedP256().y() = _ec_keys_enc.get()->public_key_y(); + } + Ieee1609Dot2BaseTypes::EciesP256EncryptedKey ecies_key(eccP256CurvePoint, _ec_keys_enc.get()->encrypted_symmetric_key(), _ec_keys_enc.get()->tag()); + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: ecies_key=", ecies_key); + + // 5. AES-128 encryption of the data + OCTETSTRING enc_message; + if (_ec_keys_enc.get()->encrypt(encryption_algotithm::aes_128_ccm, _ec_keys_enc.get()->symmetric_encryption_key(), _ec_keys_enc.get()->nonce(), + p_unsecured_gn_payload, enc_message) == -1) { + loggers::get_instance().warning("fx__encryptWithEciesNistp256WithSha256: Failed to encrypt message"); + return -1; + } + OCTETSTRING nonce = _ec_keys_enc.get()->nonce(); + OCTETSTRING tag = _ec_keys_enc.get()->tag(); + Ieee1609Dot2::AesCcmCiphertext aes_128_ccm(nonce, enc_message + tag); // Add tag at the end of the ciphered text + // 6. Build SymmetricCiphertext + Ieee1609Dot2::SymmetricCiphertext cipher_text; + cipher_text.aes128ccm() = aes_128_ccm; + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: aes_128_ccm=", cipher_text); + + // 7. Build the recipient_id + OCTETSTRING recipient_id; + _security_db.get()->get_hashed_id(certificate_id, recipient_id); // SHA-256 of the certificate which contain the recipient's public keys + + // 8. Build the encryption data + Ieee1609Dot2::EncryptedDataEncryptionKey enc_data_key; + if (_params[params::cypher].compare("NISTP-256") == 0) { + enc_data_key.eciesNistP256() = ecies_key; + } else if (_params[params::cypher].compare("BP-256") == 0) { + enc_data_key.eciesBrainpoolP256r1() = ecies_key; + } + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: enc_data_key=", enc_data_key); + + // 9. Finalise the encryption + Ieee1609Dot2::PKRecipientInfo cert_recipient_info(recipient_id, enc_data_key); + Ieee1609Dot2::RecipientInfo recipient_info; + recipient_info.certRecipInfo() = cert_recipient_info; + Ieee1609Dot2::SequenceOfRecipientInfo recipients; + recipients[0] = recipient_info; + Ieee1609Dot2::EncryptedData encrypted_data(recipients, cipher_text); + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: encrypted_data=", encrypted_data); + + // 10. Encode it + Ieee1609Dot2::Ieee1609Dot2Content ieee_dot2_content; + ieee_dot2_content.encryptedData() = encrypted_data; + Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data(security_services::ProtocolVersion, ieee_dot2_content); + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: ieee_1609dot2_data=", ieee_1609dot2_data); + etsi_ts103097_data_codec codec; + codec.encode(ieee_1609dot2_data, p_enc_gn_payload); + if (!p_enc_gn_payload.is_bound()) { + loggers::get_instance().warning("security_services::encrypt_gn_payload: Failed to encode Ieee1609Dot2Data"); + return -1; + } + loggers::get_instance().log_msg("security_services::encrypt_gn_payload: Encoded ieee_1609dot2_data=", p_enc_gn_payload); + + return 0; +} + +int security_services::decrypt_gn_payload(const OCTETSTRING &p_enc_gn_payload, OCTETSTRING &p_unsecured_gn_payload, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::decrypt_gn_payload: ", p_enc_gn_payload); + + // Sanity checks + if (_ec_keys_enc.get() == nullptr) { + loggers::get_instance().warning("security_services::decrypt_gn_payload: Encryption not initialised"); + return -1; + } + + // 1. Decode the IEEE 1609dot2Data-Encrypted + Ieee1609Dot2::Ieee1609Dot2Data ieee_1609dot2_data; + etsi_ts103097_data_codec codec; + codec.decode(p_enc_gn_payload, ieee_1609dot2_data); + if (!ieee_1609dot2_data.is_bound()) { + loggers::get_instance().warning("security_services::decrypt_gn_payload: Failed to decode Ieee1609Dot2Data-Encrypted"); + return -1; + } + loggers::get_instance().log_msg("security_services::decrypt_gn_payload: Ieee1609Dot2Data-Encrypted=", ieee_1609dot2_data); + + if (!ieee_1609dot2_data.content().ischosen(Ieee1609Dot2::Ieee1609Dot2Content::ALT_encryptedData)) { + loggers::get_instance().warning("security_services::decrypt_gn_payload: Failed to decode Decrypt Ieee1609Dot2Data-Encrypted"); + return -1; + } + if (process_ieee_1609_dot2_encrypted_data(ieee_1609dot2_data.content().encryptedData(), true, p_unsecured_gn_payload, p_params) == -1) { + loggers::get_instance().warning("security_services::decrypt_gn_payload: Failed to decode Decrypt Ieee1609Dot2Data-Encrypted"); + return -1; + } + loggers::get_instance().log_msg("security_services::decrypt_gn_payload: Encoded ieee_1609dot2_data=", p_unsecured_gn_payload); + + return 0; +} + +int security_services::sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, + const OCTETSTRING &p_private_key, Ieee1609Dot2BaseTypes::Signature &p_signature, + params &p_params) { // TODO Refine function + loggers::get_instance().log_msg(">>> security_services::sign_tbs_data: ", p_tbs_data); + + // Encode the ToBeSignedData + etsi_ts103097_tobesigned_data_codec tbs_data_codec; + OCTETSTRING os; + tbs_data_codec.encode(p_tbs_data, os); + if (os.lengthof() == 0) { + loggers::get_instance().warning("security_services::sign_tbs_data: Failed to encode ToBeSignedData"); + return -1; + } + loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded tbs_data=", os); + // Hash ToBeSignedData + OCTETSTRING hashed_data; + OCTETSTRING hash_issuer; + if (p_hashAlgorithm == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { + sha256 hash; + hash.generate(os, hashed_data); + hash_issuer = hash.get_sha256_empty_string(); + } else { + sha384 hash; + hash.generate(os, hashed_data); + hash_issuer = hash.get_sha384_empty_string(); + } + loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded hashed_data=", hashed_data); + loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded hashed_issuer=", hash_issuer); + // Sign ToBeSignedData + loggers::get_instance().log("security_services::sign_tbs_data: encoded params::signature = '%s'", + p_params[params::signature].c_str()); // TODO this parameter is useless, use content of the certificate + loggers::get_instance().log("security_services::sign_tbs_data: encoded params::certificate = '%s'", p_params[params::certificate].c_str()); + if (p_params[params::signature].compare("NISTP-256") == 0) { + // Hash ( Hash (Data input) || Hash ("") ) + OCTETSTRING os = hashed_data + hash_issuer; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::sign_tbs_data: hash: ", os); + OCTETSTRING hashed_data; + hash_sha256(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + security_ecc k(ec_elliptic_curves::nist_p_256, p_private_key); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashed_data, r_sig, s_sig) != 0) { + loggers::get_instance().warning("security_services::sign_tbs_data: Failed to sign payload"); + return -1; + } + Ieee1609Dot2BaseTypes::EccP256CurvePoint ep; + ep.x__only() = r_sig; + p_signature.ecdsaNistP256Signature() = Ieee1609Dot2BaseTypes::EcdsaP256Signature(ep, s_sig); + loggers::get_instance().log_msg("security_services::sign_tbs_data: signature=", p_signature); + } // TODO To be done + + return 0; +} + +int security_services::sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, + Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::sign_tbs_data: ", p_tbs_data); + + // Get certificate + loggers::get_instance().log("security_services::sign_tbs_data: encoded params::certificate = '%s'", p_params[params::certificate].c_str()); + // TODO Remove signature paramter, use certificate only, check if it is okay for GN with device_mode set and not setxs + // _security_db.get()->get_certificate(p_params[params::certificate]); + + // Encode the ToBeSignedData + etsi_ts103097_tobesigned_data_codec tbs_data_codec; + OCTETSTRING os; + tbs_data_codec.encode(p_tbs_data, os); + if (os.lengthof() == 0) { + loggers::get_instance().warning("security_services::sign_tbs_data: Failed to encode ToBeSignedData"); + return -1; + } + loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded tbs_data=", os); + // Hash ToBeSignedData + OCTETSTRING hashed_data; + if (p_hashAlgorithm == Ieee1609Dot2BaseTypes::HashAlgorithm::sha256) { + hash_sha256(os, hashed_data); + } else { + hash_sha384(os, hashed_data); + } + loggers::get_instance().log_msg("security_services::sign_tbs_data: encoded hashed_data=", hashed_data); + // Sign ToBeSignedData + int result = -1; + loggers::get_instance().log("security_services::sign_tbs_data: encoded params::signature = '%s'", + p_params[params::signature].c_str()); // TODO this parameter is useless, use content of the certificate + loggers::get_instance().log("security_services::sign_tbs_data: encoded params::certificate = '%s'", p_params[params::certificate].c_str()); + if (p_params[params::signature].compare("NISTP-256") == 0) { + result = sign_ecdsa_nistp256(hashed_data, p_signature, p_params); + } else if (p_params[params::signature].compare("BP-256") == 0) { + // result = sign_ecdsa_brainpoolp256r1(hashed_data, p_signature, p_params); + loggers::get_instance().error("security_services::sign_tbs_data: TODO"); + result = -1; + } else if (p_params[params::signature].compare("BP-384") == 0) { + // result = sign_ecdsa_brainpoolp384r1(hashed_data, p_signature, p_params); + loggers::get_instance().error("security_services::sign_tbs_data: TODO"); + result = -1; + } else { + loggers::get_instance().error("security_services::sign_tbs_data: Unsupported signature algorithm"); + result = -1; + } + if (result != 0) { + loggers::get_instance().warning("security_services::sign_tbs_data: Failed to sign payload"); + return -1; + } + + return 0; +} + +int security_services::hash_sha256(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data) { + loggers::get_instance().log_msg(">>> security_services::hash_sha256: ", p_data); + + sha256 hash; + return hash.generate(p_data, p_hash_data); +} + +int security_services::hash_sha384(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data) { + loggers::get_instance().log_msg(">>> security_services::hash_sha384: ", p_data); + + sha384 hash; + return hash.generate(p_data, p_hash_data); +} + +int security_services::sign_ecdsa_nistp256(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::sign_ecdsa_nistp256: ", p_hash); + + std::string certificate_id = p_params[params::certificate]; + loggers::get_instance().log("security_services::sign_ecdsa_nistp256: encoded certificate_id = '%s'", certificate_id.c_str()); + OCTETSTRING pkey; + if (_security_db->get_private_key(certificate_id, pkey) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_nistp256: Failed to get private key"); + return -1; + } + // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + OCTETSTRING hash_cert; + if (_security_db->get_hash(certificate_id, hash_cert) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_nistp256: Failed to get whole hash certificate"); + return -1; + } + loggers::get_instance().log_msg("security_services::sign_ecdsa_nistp256: hash_issuer: ", hash_cert); + OCTETSTRING os = p_hash + hash_cert; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::sign_ecdsa_nistp256: hash: ", os); + OCTETSTRING hashed_data; + hash_sha256(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + security_ecc k(ec_elliptic_curves::nist_p_256, pkey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashed_data, r_sig, s_sig) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_nistp256: Failed to sign payload"); + return -1; + } + Ieee1609Dot2BaseTypes::EccP256CurvePoint ep; + ep.x__only() = r_sig; + p_signature.ecdsaNistP256Signature() = Ieee1609Dot2BaseTypes::EcdsaP256Signature(ep, s_sig); + loggers::get_instance().log_msg("security_services::sign_ecdsa_nistp256: signature=", p_signature); + + return 0; +} + +int security_services::verify_sign_ecdsa_nistp256(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, + const std::string &p_certificate_id, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::verify_sign_ecdsa_nistp256:", p_hash); + loggers::get_instance().log(">>> security_services::verify_sign_ecdsa_nistp256: %s", p_certificate_id.c_str()); + + OCTETSTRING public_key_x; + OCTETSTRING public_key_y; + if (_security_db->get_public_keys(p_certificate_id, public_key_x, public_key_y) != 0) { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_nistp256 (%s): Failed to get public keys", p_certificate_id.c_str()); + return -1; + } + + // Generate the hash to be verified: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + OCTETSTRING issuer; // Hash (Signer identifier input) + if (_security_db->get_hash(p_certificate_id, issuer) != 0) { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_nistp256 (%s): Failed to get hash of the issuer certificate", + p_certificate_id.c_str()); + return -1; + } + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_nistp256: hash_issuer: ", issuer); + OCTETSTRING hash_data = p_hash + issuer; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_nistp256: hash: ", hash_data); + OCTETSTRING hash_to_be_verified; + hash_sha256(hash_data, hash_to_be_verified); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_nistp256: hash_to_be_verified: ", hash_to_be_verified); + + // Build the signature + OCTETSTRING signature; + if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_x__only)) { + signature = p_signature.ecdsaNistP256Signature().rSig().x__only() + p_signature.ecdsaNistP256Signature().sSig(); + } else if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + signature = p_signature.ecdsaNistP256Signature().rSig().compressed__y__0() + p_signature.ecdsaNistP256Signature().sSig(); + } else if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + signature = p_signature.ecdsaNistP256Signature().rSig().compressed__y__1() + p_signature.ecdsaNistP256Signature().sSig(); + } else if (p_signature.ecdsaNistP256Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + signature = p_signature.ecdsaNistP256Signature().rSig().uncompressedP256().x() + p_signature.ecdsaNistP256Signature().rSig().uncompressedP256().y() + + p_signature.ecdsaNistP256Signature().sSig(); + } else { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_nistp256 (%s): Invalid curve point", p_certificate_id.c_str()); + return -1; + } + security_ecc k(ec_elliptic_curves::nist_p_256, public_key_x, public_key_y); + if (k.sign_verif(hash_to_be_verified, signature) == 0) { + return 0; + } + + return -1; +} + +int security_services::sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::sign_ecdsa_brainpoolp256r1: ", p_hash); + + std::string certificate_id = p_params[params::certificate]; + loggers::get_instance().log("security_services::sign_ecdsa_brainpoolp256r1: encoded certificate_id = '%s'", certificate_id.c_str()); + OCTETSTRING pkey; + if (_security_db->get_private_key(certificate_id, pkey) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp256r1: Failed to get private key"); + return -1; + } + // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + OCTETSTRING hash_cert; + if (_security_db->get_hash(certificate_id, hash_cert) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp256r1: Failed to get whole hash certificate"); + return -1; + } + loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp256r1: hash_issuer: ", hash_cert); + OCTETSTRING os = p_hash + hash_cert; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp256r1: hash: ", os); + OCTETSTRING hashed_data; + hash_sha256(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, pkey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashed_data, r_sig, s_sig) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp256r1: Failed to sign payload"); + return -1; + } + Ieee1609Dot2BaseTypes::EccP256CurvePoint ep; + ep.x__only() = r_sig; + p_signature.ecdsaBrainpoolP256r1Signature() = Ieee1609Dot2BaseTypes::EcdsaP256Signature(ep, s_sig); + loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp256r1: signature=", p_signature); + + return 0; +} + +int security_services::verify_sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, + const std::string &p_certificate_id, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::verify_sign_ecdsa_brainpoolp256r1:", p_hash); + loggers::get_instance().log(">>> security_services::verify_sign_ecdsa_brainpoolp256r1: %s", p_certificate_id.c_str()); + + OCTETSTRING public_key_x; + OCTETSTRING public_key_y; + if (_security_db->get_public_keys(p_certificate_id, public_key_x, public_key_y) != 0) { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp256r1 (%s): Failed to get public keys", p_certificate_id.c_str()); + return -1; + } + + // Generate the hash to be verified: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + OCTETSTRING issuer; // Hash (Signer identifier input) + if (_security_db->get_hash(p_certificate_id, issuer) != 0) { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp256r1 (%s): Failed to get hash of the issuer certificate", + p_certificate_id.c_str()); + return -1; + } + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp256r1: hash_issuer: ", issuer); + OCTETSTRING hash_data = p_hash + issuer; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp256r1: hash: ", hash_data); + OCTETSTRING hash_to_be_verified; + hash_sha256(hash_data, hash_to_be_verified); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp256r1: hash_to_be_verified: ", hash_to_be_verified); + + // Build the signature + OCTETSTRING signature; + if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_x__only)) { + signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().x__only() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); + } else if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().compressed__y__0() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); + } else if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().compressed__y__1() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); + } else if (p_signature.ecdsaBrainpoolP256r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + signature = p_signature.ecdsaBrainpoolP256r1Signature().rSig().uncompressedP256().x() + + p_signature.ecdsaBrainpoolP256r1Signature().rSig().uncompressedP256().y() + p_signature.ecdsaBrainpoolP256r1Signature().sSig(); + } else { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp256r1 (%s): Invalid curve point", p_certificate_id.c_str()); + return -1; + } + security_ecc k(ec_elliptic_curves::brainpool_p_256_r1, public_key_x, public_key_y); + if (k.sign_verif(hash_to_be_verified, signature) == 0) { + return 0; + } + + return -1; +} + +int security_services::sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::sign_ecdsa_brainpoolp384r1: ", p_hash); + + std::string certificate_id = p_params[params::certificate]; + loggers::get_instance().log("security_services::sign_ecdsa_brainpoolp384r1: encoded certificate_id = '%s'", certificate_id.c_str()); + OCTETSTRING pkey; + if (_security_db->get_private_key(certificate_id, pkey) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp384r1: Failed to get private key"); + return -1; + } + // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + OCTETSTRING hash_cert; + if (_security_db->get_hash(certificate_id, hash_cert) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp384r1: Failed to get whole hash certificate"); + return -1; + } + loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp384r1: hash_issuer: ", hash_cert); + OCTETSTRING os = p_hash + hash_cert; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp384r1: hash: ", os); + OCTETSTRING hashed_data; + hash_sha384(os, hashed_data); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, pkey); + OCTETSTRING r_sig; + OCTETSTRING s_sig; + if (k.sign(hashed_data, r_sig, s_sig) != 0) { + loggers::get_instance().warning("security_services::sign_ecdsa_brainpoolp384r1: Failed to sign payload"); + return -1; + } + Ieee1609Dot2BaseTypes::EccP384CurvePoint ep; + ep.x__only() = r_sig; + p_signature.ecdsaBrainpoolP384r1Signature() = Ieee1609Dot2BaseTypes::EcdsaP384Signature(ep, s_sig); + loggers::get_instance().log_msg("security_services::sign_ecdsa_brainpoolp384r1: signature=", p_signature); + + return 0; +} + +int security_services::verify_sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, + const std::string &p_certificate_id, params &p_params) { + loggers::get_instance().log_msg(">>> security_services::verify_sign_ecdsa_brainpoolp384r1:", p_hash); + loggers::get_instance().log(">>> security_services::verify_sign_ecdsa_brainpoolp384r1: %s", p_certificate_id.c_str()); + + OCTETSTRING public_key_x; + OCTETSTRING public_key_y; + if (_security_db->get_public_keys(p_certificate_id, public_key_x, public_key_y) != 0) { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp384r1 (%s): Failed to get public keys", p_certificate_id.c_str()); + return -1; + } + + // Generate the hash to be verified: Hash ( Hash (Data input) || Hash (Signer identifier input) ) + OCTETSTRING issuer; // Hash (Signer identifier input) + if (_security_db->get_hash(p_certificate_id, issuer) != 0) { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp384r1 (%s): Failed to get hash of the issuer certificate", + p_certificate_id.c_str()); + return -1; + } + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp384r1: hash_issuer: ", issuer); + OCTETSTRING hash_data = p_hash + issuer; // Hash (Data input) || Hash (Signer identifier input) + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp384r1: hash: ", hash_data); + OCTETSTRING hash_to_be_verified; + hash_sha384(hash_data, hash_to_be_verified); // Hash ( Hash (Data input) || Hash (Signer identifier input) ) + loggers::get_instance().log_msg("security_services::verify_sign_ecdsa_brainpoolp384r1: hash_to_be_verified: ", hash_to_be_verified); + + // Build the signature + OCTETSTRING signature; + if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_x__only)) { + signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().x__only() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); + } else if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__0)) { + signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().compressed__y__0() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); + } else if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__1)) { + signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().compressed__y__1() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); + } else if (p_signature.ecdsaBrainpoolP384r1Signature().rSig().ischosen(Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_uncompressedP384)) { + signature = p_signature.ecdsaBrainpoolP384r1Signature().rSig().uncompressedP384().x() + + p_signature.ecdsaBrainpoolP384r1Signature().rSig().uncompressedP384().y() + p_signature.ecdsaBrainpoolP384r1Signature().sSig(); + } else { + loggers::get_instance().warning("security_services::verify_sign_ecdsa_brainpoolp384r1 (%s): Invalid curve point", p_certificate_id.c_str()); + return -1; + } + security_ecc k(ec_elliptic_curves::brainpool_p_384_r1, public_key_x, public_key_y); + if (k.sign_verif(hash_to_be_verified, signature) == 0) { + return 0; + } + + return -1; +} + +int security_services::extract_verification_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y, + OCTETSTRING &p_public_comp_key, INTEGER &p_public_comp_key_mode) { + loggers::get_instance().log("security_services::extract_verification_keys"); + + if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaNistP256)) { + if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().compressed__y__0(); + security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_comp_key, ecc_compressed_mode::compressed_y_0); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + p_public_comp_key_mode = INTEGER(0); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().ischosen( + Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().compressed__y__1(); + security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_comp_key, ecc_compressed_mode::compressed_y_1); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + p_public_comp_key_mode = INTEGER(1); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().ischosen( + Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + security_ecc ecc(ec_elliptic_curves::nist_p_256, p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().x(), + p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().y()); + p_public_comp_key = ecc.public_key_compressed(); + p_public_comp_key_mode = INTEGER((int)ecc.public_key_compressed_mode()); + p_public_key_x = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().x(); + p_public_key_y = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaNistP256().uncompressedP256().y(); + } else { + loggers::get_instance().error("security_services::extract_verification_keys: Unsupported VerificationKey"); + return -1; + } + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaBrainpoolP256r1)) { + if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().ischosen( + Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().compressed__y__0(); + security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_0); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + p_public_comp_key_mode = INTEGER(0); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().ischosen( + Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().compressed__y__1(); + security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_1); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + p_public_comp_key_mode = INTEGER(1); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().ischosen( + Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + p_public_key_x = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().uncompressedP256().x(); + p_public_key_y = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP256r1().uncompressedP256().y(); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ischosen(Ieee1609Dot2BaseTypes::PublicVerificationKey::ALT_ecdsaBrainpoolP384r1)) { + p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().compressed__y__0(); + security_ecc ecc(ec_elliptic_curves::brainpool_p_384_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_0); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + p_public_comp_key_mode = INTEGER(0); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().ischosen( + Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_compressed__y__1)) { + p_public_comp_key = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().compressed__y__1(); + security_ecc ecc(ec_elliptic_curves::brainpool_p_384_r1, p_public_comp_key, ecc_compressed_mode::compressed_y_1); + p_public_key_x = ecc.public_key_x(); + p_public_key_y = ecc.public_key_y(); + p_public_comp_key_mode = INTEGER(1); + } else if (p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().ischosen( + Ieee1609Dot2BaseTypes::EccP384CurvePoint::ALT_uncompressedP384)) { + p_public_key_x = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().uncompressedP384().x(); + p_public_key_y = p_cert.toBeSigned().verifyKeyIndicator().verificationKey().ecdsaBrainpoolP384r1().uncompressedP384().y(); + } else { + loggers::get_instance().error("security_services::extract_verification_keys: Unsupported VerificationKey"); + return -1; + } + } else { + loggers::get_instance().error("security_services::extract_verification_keys: Unsupported VerificationKey"); + return -1; + } + + return 0; +} + +int security_services::extract_encryption_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y, + OCTETSTRING &p_public_enc_comp_key, INTEGER &p_public_enc_comp_key_mode) { + loggers::get_instance().log("security_services::extract_encryption_keys"); + + if (p_cert.toBeSigned().encryptionKey().ispresent()) { + const Ieee1609Dot2BaseTypes::PublicEncryptionKey &p = static_cast(p_cert.toBeSigned().encryptionKey()); + if (p.publicKey().ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesNistP256)) { + if (p.publicKey().eciesNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + p_public_enc_comp_key = p.publicKey().eciesNistP256().compressed__y__0(); + security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_0); + p_public_enc_key_x = ecc.public_key_x(); + p_public_enc_key_y = ecc.public_key_y(); + p_public_enc_comp_key_mode = INTEGER(0); + } else if (p.publicKey().eciesNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + const OCTETSTRING &p_public_enc_comp_key = p.publicKey().eciesNistP256().compressed__y__1(); + security_ecc ecc(ec_elliptic_curves::nist_p_256, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_1); + p_public_enc_key_x = ecc.public_key_x(); + p_public_enc_key_y = ecc.public_key_y(); + p_public_enc_comp_key_mode = INTEGER(1); + } else if (p.publicKey().eciesNistP256().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + p_public_enc_key_x = p.publicKey().eciesNistP256().uncompressedP256().x(); + p_public_enc_key_y = p.publicKey().eciesNistP256().uncompressedP256().y(); + } else { + loggers::get_instance().error("security_services::extract_encryption_keys: Unsupported EncryptionKey"); + return -1; + } + } else if (p.publicKey().ischosen(Ieee1609Dot2BaseTypes::BasePublicEncryptionKey::ALT_eciesBrainpoolP256r1)) { + if (p.publicKey().eciesBrainpoolP256r1().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__0)) { + p_public_enc_comp_key = p.publicKey().eciesBrainpoolP256r1().compressed__y__0(); + security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_0); + p_public_enc_key_x = ecc.public_key_x(); + p_public_enc_key_y = ecc.public_key_y(); + p_public_enc_comp_key_mode = INTEGER(0); + } else if (p.publicKey().eciesBrainpoolP256r1().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_compressed__y__1)) { + p_public_enc_comp_key = p.publicKey().eciesBrainpoolP256r1().compressed__y__1(); + security_ecc ecc(ec_elliptic_curves::brainpool_p_256_r1, p_public_enc_comp_key, ecc_compressed_mode::compressed_y_1); + p_public_enc_key_x = ecc.public_key_x(); + p_public_enc_key_y = ecc.public_key_y(); + p_public_enc_comp_key_mode = INTEGER(1); + } else if (p.publicKey().eciesBrainpoolP256r1().ischosen(Ieee1609Dot2BaseTypes::EccP256CurvePoint::ALT_uncompressedP256)) { + p_public_enc_key_x = p.publicKey().eciesBrainpoolP256r1().uncompressedP256().x(); + p_public_enc_key_y = p.publicKey().eciesBrainpoolP256r1().uncompressedP256().y(); + } else { + loggers::get_instance().error("security_services::extract_encryption_keys: Unsupported EncryptionKey"); + return -1; + } + } else { + loggers::get_instance().error("security_services::extract_encryption_keys: Unsupported EncryptionKey"); + return -1; + } + } else { + loggers::get_instance().warning("security_services::extract_encryption_keys: EncryptionKey omitted"); + p_public_enc_key_x = OCTETSTRING(0, nullptr); + p_public_enc_key_y = OCTETSTRING(0, nullptr); + p_public_enc_comp_key = OCTETSTRING(0, nullptr); + return 0; // Normal termination + } + + return 0; +} // End of method extract_encryption_keys + +int security_services::extract_and_store_certificate(const Ieee1609Dot2::CertificateBase &p_certificate, std::string &p_certificate_id) { + loggers::get_instance().log_msg(">>> security_services::extract_and_store_certificate: ", p_certificate); + + // Encode certificate + etsi_ts103097_certificate_codec codec; + OCTETSTRING enc_cert; + codec.encode(p_certificate, enc_cert); + if (enc_cert.lengthof() == 0) { + loggers::get_instance().warning("security_services::extract_and_store_certificate: Failed to encode certificate"); + return -1; + } + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Encoded certificate=", enc_cert); + OCTETSTRING hash_cert_sha_256; + hash_sha256(enc_cert, hash_cert_sha_256); + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: hash_cert_sha_256= ", hash_cert_sha_256); + int result = -1; + if (p_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha256AndDigest)) { + // Calculate the hash according to the hashId + OCTETSTRING hash_cert(hash_cert_sha_256); + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: hash_cert= ", hash_cert); + const OCTETSTRING hashed_id8 = substr(hash_cert, hash_cert.lengthof() - 8, 8); + // Retrieve the certificate identifier from digest + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Retrieve the certificate identifier from digest: ", hashed_id8); + result = _security_db.get()->get_certificate_id(hashed_id8, p_certificate_id); + if (result == -1) { // Not found in current DB + if (_security_cache.get()->get_certificate_id(hashed_id8, p_certificate_id) == -1) { // Not found in TS cache + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Store new certificate in cache: ", p_certificate); + // const std::vector v(static_cast(hashed_id8), static_cast(hashed_id8) + + // hashed_id8.lengthof()); p_certificate_id = converter::get_instance().bytes_to_hexa(v); + p_certificate_id = std::string(static_cast(hex2str(oct2hex(hashed_id8)))); + // Add it into the cache + OCTETSTRING public_key_x, public_key_y, public_comp_key; + INTEGER public_comp_key_mode; + if (extract_verification_keys(p_certificate, public_key_x, public_key_y, public_comp_key, public_comp_key_mode) == -1) { + loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); + return -1; + } + // Add encryption keys + OCTETSTRING public_enc_key_x, public_enc_key_y, public_enc_comp_key; + INTEGER public_enc_comp_key_mode; + if (extract_encryption_keys(p_certificate, public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode) == -1) { + loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); + return -1; + } + // And store it into the cache + _security_cache.get()->store_certificate(CHARSTRING(p_certificate_id.c_str()), enc_cert, int2oct(0, 32), // No way to get the private key here + public_key_x, public_key_y, public_comp_key, public_comp_key_mode, hash_cert, hash_cert_sha_256, hashed_id8, + p_certificate.issuer().sha256AndDigest(), OCTETSTRING(0, nullptr), // Encryption private not used + public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode); + } + } + } else if (p_certificate.issuer().ischosen(Ieee1609Dot2::IssuerIdentifier::ALT_sha384AndDigest)) { + // Calculate the hash according to the hashId + OCTETSTRING hash_cert; + hash_sha384(enc_cert, hash_cert); + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: hash_cert= ", hash_cert); + const OCTETSTRING hashed_id8 = substr(hash_cert, hash_cert.lengthof() - 8, 8); + // Retrieve the certificate identifier from digest + loggers::get_instance().log("security_services::extract_and_store_certificate: Retrieve the certificate identifier from digest"); + result = _security_db.get()->get_certificate_id(hashed_id8, p_certificate_id); + if (result == -1) { + if (_security_cache.get()->get_certificate_id(hashed_id8, p_certificate_id) == -1) { + loggers::get_instance().log_msg("security_services::extract_and_store_certificate: Store new certificate in cache: ", p_certificate); + // const std::vector v(static_cast(hashed_id8), static_cast(hashed_id8) + + // hashed_id8.lengthof()); p_certificate_id = converter::get_instance().bytes_to_hexa(v); + p_certificate_id = std::string(static_cast(hex2str(oct2hex(hashed_id8)))); + // Add it into the cache + OCTETSTRING public_key_x, public_key_y, public_comp_key; + INTEGER public_comp_key_mode; + if (extract_verification_keys(p_certificate, public_key_x, public_key_y, public_comp_key, public_comp_key_mode) == -1) { + loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); + return -1; + } + // Add encryption keys + OCTETSTRING public_enc_key_x, public_enc_key_y, public_enc_comp_key; + INTEGER public_enc_comp_key_mode; + if (extract_encryption_keys(p_certificate, public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode) == -1) { + loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported EncryptionKey"); + return -1; + } + // And store it into the cache + _security_cache.get()->store_certificate(CHARSTRING(p_certificate_id.c_str()), enc_cert, int2oct(0, 48), // No way to get the private key here + public_key_x, public_key_y, public_comp_key, public_comp_key_mode, hash_cert, hash_cert_sha_256, hashed_id8, + p_certificate.issuer().sha384AndDigest(), OCTETSTRING(0, nullptr), // Encryption private not used + public_enc_key_x, public_enc_key_y, public_enc_comp_key, public_enc_comp_key_mode); + } + } + } else { + loggers::get_instance().error("security_services::extract_and_store_certificate: Unsupported issuer"); + return -1; + } + + return 0; +} // End of method extract_and_store_certificate + +int security_services::read_certificate(const CHARSTRING &p_certificate_id, OCTETSTRING &p_certificate) const { + return _security_db.get()->get_certificate(std::string(static_cast(p_certificate_id)), p_certificate); +} + +int security_services::read_certificate_digest(const CHARSTRING &p_certificate_id, OCTETSTRING &p_digest) const { + return _security_db.get()->get_hashed_id(std::string(static_cast(p_certificate_id)), p_digest); +} + +int security_services::read_certificate_hash(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const { + return _security_db.get()->get_hash(std::string(static_cast(p_certificate_id)), p_hash); +} + +int security_services::read_certificate_hash_sha_256(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const { + return _security_db.get()->get_hash_sha_256(std::string(static_cast(p_certificate_id)), p_hash); +} + +int security_services::read_certificate_from_digest(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const { + std::string certificate_id; + if (_security_db.get()->get_certificate_id(p_digest, certificate_id) != -1) { + p_certificate_id = CHARSTRING(certificate_id.c_str()); + return 0; + } + return -1; +} + +int security_services::read_certificate_from_hashed_id3(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const { + std::string certificate_id; + if (_security_db.get()->get_certificate_hashed_id3(p_digest, certificate_id) != -1) { + p_certificate_id = CHARSTRING(certificate_id.c_str()); + return 0; + } + return -1; +} + +int security_services::read_private_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_key) const { + return _security_db.get()->get_private_key(std::string(static_cast(p_certificate_id)), p_private_key); +} + +int security_services::read_private_enc_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_enc_key) const { + return _security_db.get()->get_private_enc_key(std::string(static_cast(p_certificate_id)), p_private_enc_key); +} diff --git a/ccsrc/Protocols/Security/security_services.hh b/ccsrc/Protocols/Security/security_services.hh index 4e4263545227d1f9e179e3ced6ba2169c6b1fb2a..696f93074630150e7981a7f58d899020640466d6 100644 --- a/ccsrc/Protocols/Security/security_services.hh +++ b/ccsrc/Protocols/Security/security_services.hh @@ -1,192 +1,192 @@ -#pragma once - -#include - -#include "params.hh" - -#include "security_db.hh" - -#include "security_ecc.hh" - -#include "geospacial.hh" - -class OCTETSTRING; //! TITAN forward declaration -class CHARSTRING; //! TITAN forward declaration - -namespace Ieee1609Dot2BaseTypes { - class HashAlgorithm; //! TITAN forward declaration - class Signature; //! TITAN forward declaration -} // namespace Ieee1609Dot2BaseTypes - -namespace Ieee1609Dot2 { - class Ieee1609Dot2Data; //! TITAN forward declaration - class Ieee1609Dot2Content; //! TITAN forward declaration - class ToBeSignedData; //! TITAN forward declaration - class SignedData; //! TITAN forward declaration - class EncryptedData; //! TITAN forward declaration - class SignerIdentifier; //! TITAN forward declaration -} // namespace Ieee1609Dot2 - -/*! - * \class security_services - * \brief This class provides security services for all layers as specified in TSI TS 102 723-8 and ETSI TS 103 097 - * \remark Singleton pattern - */ -class security_services { - - static constexpr unsigned int ProtocolVersion = 3; - - /*! - * \brief Unique static object reference of this class - */ - static security_services *instance; - - params _params; - bool _setup_done; - std::unique_ptr _ec_keys_enc; - std::unique_ptr _ec_keys_dec; - std::unique_ptr _security_cache; - std::unique_ptr _security_db; - unsigned long long _last_generation_time; - OCTETSTRING _unknown_certificate; - std::vector _requested_certificate; - int _latitude; - int _longitude; - int _elevation; - geospacial _geospacial; - - /*! - * \brief Default private ctor - */ - security_services(); - /*! - * \brief Default private dtor - */ - ~security_services() { - _ec_keys_enc.reset(nullptr); - _security_db.reset(nullptr); - _security_cache.reset(nullptr); - if (instance != NULL) { - delete instance; - instance = NULL; - } - }; - -public: /*! \publicsection */ - /*! - * \brief Public accessor to the single object reference - */ - inline static security_services &get_instance() { - if (instance == NULL) - instance = new security_services(); - return *instance; - }; - - /*! - * \fn int verify_and_extract_gn_payload(const OCTETSTRING& p_secured_gn_payload, const bool p_verify, OCTETSTRING& p_unsecured_gn_payload, params& p_params); - * \brief Verify and extract the unsecured payload from the provided secured payload. - * The secured payload could signed only, encryted only or signed and encrypted - * \param[in] p_secured_gn_payload The secured payload to be processed - * \param[in] p_verify Set to true if security checks shall be applied - * \param[out] p_unsecured_gn_payload The extracted payload - * \param[out] p_ieee_1609dot2_data The secured message - * \param[inout] p_params The Test System parameters - * \return 0 on success, negative value otherwise - */ - int verify_and_extract_gn_payload(const OCTETSTRING &p_secured_gn_payload, const bool p_verify, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, - OCTETSTRING &p_unsecured_gn_payload, params &p_params); - /*! - * \fn int secure_gn_payload(const OCTETSTRING& p_unsecured_gn_payload, OCTETSTRING& p_secured_gn_payload, params& p_params); - * \brief Apply security to the provided unsecured payload - * \param[in] p_unsecured_gn_payload The unsecured payload to be processed - * \param[in] p_secured_gn_payload The secured payload - * \param[in] p_params The Test System parameters - * \return 0 on success, negative value otherwise - */ - int secure_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_secured_gn_payload, params &p_params); - - int setup(params &p_params); - - int store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, - const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_comp_key, const INTEGER &p_public_comp_key_mode, - const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, - const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, - const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_key_compressed_mode); - - inline void set_position(const int p_latitude, const int p_longitude, const int p_elevation = 0) { - _latitude = p_latitude; - _longitude = p_longitude; - _elevation = p_elevation; - }; - - int read_certificate(const CHARSTRING &p_certificate_id, OCTETSTRING &p_certificate) const; - int read_certificate_digest(const CHARSTRING &p_certificate_id, OCTETSTRING &p_digest) const; - int read_certificate_hash(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const; - int read_certificate_hash_sha_256(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const; - int read_certificate_from_digest(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const; - int read_certificate_from_hashed_id3(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const; - int read_private_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_key) const; - int read_private_enc_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_enc_key) const; - - /*! - * \fn int sign_payload(const OCTETSTRING& p_unsecured_gn_payload, OCTETSTRING& p_signed_gn_payload, params& p_params); - * \brief Sign the payload according provided parameters - * \param[in] p_unsecured_gn_payload The payload to be signed - * \param[in] p_signed_gn_payload The signed payload - * \param[in] p_params The Test System parameters - * \return 0 on success, negative value otherwise - */ - int sign_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_signed_gn_payload, params &p_params); - /*! - * \fn int encrypt_gn_payload(const OCTETSTRING& p_unsecured_gn_payload, OCTETSTRING& p_signed_gn_payload, params& p_params); - * \brief Encrypt the payload according provided parameters - * \param[in] p_unsecured_gn_payload The payload to be encrypted - * \param[in] p_enc_gn_payload The encrypted payload - * \param[in] p_params The Test System parameters - * \return 0 on success, negative value otherwise - */ - int encrypt_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_enc_gn_payload, params &p_params); - - int decrypt_gn_payload(const OCTETSTRING &p_enc_gn_payload, OCTETSTRING &p_unsecured_gn_payload, params &p_params); - - int sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, - const OCTETSTRING &p_private_key, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); - - const int get_protocol_version() const { return ProtocolVersion; }; - -private: - /*! - * \fn int process_ieee_1609_dot2_content(const Ieee1609Dot2::Ieee1609Dot2Content& p_ieee_1609_dot2_content, const bool p_verify, OCTETSTRING& - * p_unsecured_payload, params& p_params); \brief Verify and extract the unsecured payload from the Ieee1609Dot2::Ieee1609Dot2Content data structure - * \param[in] p_content The secured content to be processed - * \param[in] p_verify Set to true if security checks shall be applied - * \param[in] p_unsecured_payload The extracted payload - * \return 0 on success, negative value otherwise - */ - int process_ieee_1609_dot2_content(const Ieee1609Dot2::Ieee1609Dot2Content &p_ieee_1609_dot2_content, const bool p_verify, OCTETSTRING &p_unsecured_payload, - params &p_params); - int process_ieee_1609_dot2_signed_data(const Ieee1609Dot2::SignedData &p_signed_data, const bool p_verify, OCTETSTRING &p_unsecured_payload, - params &p_params); - int process_ieee_1609_dot2_encrypted_data(const Ieee1609Dot2::EncryptedData &p_encrypted_data, const bool p_verify, OCTETSTRING &p_unsecured_payload, - params &p_params); - int sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, - Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); - - int hash_sha256(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data); - int hash_sha384(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data); - int sign_ecdsa_nistp256(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); - int sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); - int sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); - int verify_sign_ecdsa_nistp256(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, const std::string &p_certificate_id, - params &p_params); - int verify_sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, const std::string &p_certificate_id, - params &p_params); - int verify_sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, const std::string &p_certificate_id, - params &p_params); - - int extract_verification_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y, - OCTETSTRING &p_public_comp_key, INTEGER &p_public_comp_key_mode); - int extract_encryption_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y, - OCTETSTRING &p_public_enc_comp_key, INTEGER &p_public_enc_comp_key_mode); - int extract_and_store_certificate(const Ieee1609Dot2::CertificateBase &p_certificate, std::string &p_certificate_id); -}; // End of class security_services +#pragma once + +#include + +#include "params.hh" + +#include "security_db.hh" + +#include "security_ecc.hh" + +#include "geospacial.hh" + +class OCTETSTRING; //! TITAN forward declaration +class CHARSTRING; //! TITAN forward declaration + +namespace Ieee1609Dot2BaseTypes { + class HashAlgorithm; //! TITAN forward declaration + class Signature; //! TITAN forward declaration +} // namespace Ieee1609Dot2BaseTypes + +namespace Ieee1609Dot2 { + class Ieee1609Dot2Data; //! TITAN forward declaration + class Ieee1609Dot2Content; //! TITAN forward declaration + class ToBeSignedData; //! TITAN forward declaration + class SignedData; //! TITAN forward declaration + class EncryptedData; //! TITAN forward declaration + class SignerIdentifier; //! TITAN forward declaration +} // namespace Ieee1609Dot2 + +/*! + * \class security_services + * \brief This class provides security services for all layers as specified in TSI TS 102 723-8 and ETSI TS 103 097 + * \remark Singleton pattern + */ +class security_services { + + static constexpr unsigned int ProtocolVersion = 3; + + /*! + * \brief Unique static object reference of this class + */ + static security_services *instance; + + params _params; + bool _setup_done; + std::unique_ptr _ec_keys_enc; + std::unique_ptr _ec_keys_dec; + std::unique_ptr _security_cache; + std::unique_ptr _security_db; + unsigned long long _last_generation_time; + OCTETSTRING _unknown_certificate; + std::vector _requested_certificate; + int _latitude; + int _longitude; + int _elevation; + geospacial _geospacial; + + /*! + * \brief Default private ctor + */ + security_services(); + /*! + * \brief Default private dtor + */ + ~security_services() { + _ec_keys_enc.reset(nullptr); + _security_db.reset(nullptr); + _security_cache.reset(nullptr); + if (instance != NULL) { + delete instance; + instance = NULL; + } + }; + +public: /*! \publicsection */ + /*! + * \brief Public accessor to the single object reference + */ + inline static security_services &get_instance() { + if (instance == NULL) + instance = new security_services(); + return *instance; + }; + + /*! + * \fn int verify_and_extract_gn_payload(const OCTETSTRING& p_secured_gn_payload, const bool p_verify, OCTETSTRING& p_unsecured_gn_payload, params& p_params); + * \brief Verify and extract the unsecured payload from the provided secured payload. + * The secured payload could signed only, encryted only or signed and encrypted + * \param[in] p_secured_gn_payload The secured payload to be processed + * \param[in] p_verify Set to true if security checks shall be applied + * \param[out] p_unsecured_gn_payload The extracted payload + * \param[out] p_ieee_1609dot2_data The secured message + * \param[inout] p_params The Test System parameters + * \return 0 on success, negative value otherwise + */ + int verify_and_extract_gn_payload(const OCTETSTRING &p_secured_gn_payload, const bool p_verify, Ieee1609Dot2::Ieee1609Dot2Data &p_ieee_1609dot2_data, + OCTETSTRING &p_unsecured_gn_payload, params &p_params); + /*! + * \fn int secure_gn_payload(const OCTETSTRING& p_unsecured_gn_payload, OCTETSTRING& p_secured_gn_payload, params& p_params); + * \brief Apply security to the provided unsecured payload + * \param[in] p_unsecured_gn_payload The unsecured payload to be processed + * \param[in] p_secured_gn_payload The secured payload + * \param[in] p_params The Test System parameters + * \return 0 on success, negative value otherwise + */ + int secure_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_secured_gn_payload, params &p_params); + + int setup(params &p_params); + + int store_certificate(const CHARSTRING &p_cert_id, const OCTETSTRING &p_cert, const OCTETSTRING &p_private_key, const OCTETSTRING &p_public_key_x, + const OCTETSTRING &p_public_key_y, const OCTETSTRING &p_public_comp_key, const INTEGER &p_public_comp_key_mode, + const OCTETSTRING &p_hash, const OCTETSTRING &p_hash_sha_256, const OCTETSTRING &p_hashid8, const OCTETSTRING &p_issuer, + const OCTETSTRING &p_private_enc_key, const OCTETSTRING &p_public_enc_key_x, const OCTETSTRING &p_public_enc_key_y, + const OCTETSTRING &p_public_enc_compressed_key, const INTEGER &p_public_enc_key_compressed_mode); + + inline void set_position(const int p_latitude, const int p_longitude, const int p_elevation = 0) { + _latitude = p_latitude; + _longitude = p_longitude; + _elevation = p_elevation; + }; + + int read_certificate(const CHARSTRING &p_certificate_id, OCTETSTRING &p_certificate) const; + int read_certificate_digest(const CHARSTRING &p_certificate_id, OCTETSTRING &p_digest) const; + int read_certificate_hash(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const; + int read_certificate_hash_sha_256(const CHARSTRING &p_certificate_id, OCTETSTRING &p_hash) const; + int read_certificate_from_digest(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const; + int read_certificate_from_hashed_id3(const OCTETSTRING &p_digest, CHARSTRING &p_certificate_id) const; + int read_private_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_key) const; + int read_private_enc_key(const CHARSTRING &p_certificate_id, OCTETSTRING &p_private_enc_key) const; + + /*! + * \fn int sign_payload(const OCTETSTRING& p_unsecured_gn_payload, OCTETSTRING& p_signed_gn_payload, params& p_params); + * \brief Sign the payload according provided parameters + * \param[in] p_unsecured_gn_payload The payload to be signed + * \param[in] p_signed_gn_payload The signed payload + * \param[in] p_params The Test System parameters + * \return 0 on success, negative value otherwise + */ + int sign_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_signed_gn_payload, params &p_params); + /*! + * \fn int encrypt_gn_payload(const OCTETSTRING& p_unsecured_gn_payload, OCTETSTRING& p_signed_gn_payload, params& p_params); + * \brief Encrypt the payload according provided parameters + * \param[in] p_unsecured_gn_payload The payload to be encrypted + * \param[in] p_enc_gn_payload The encrypted payload + * \param[in] p_params The Test System parameters + * \return 0 on success, negative value otherwise + */ + int encrypt_gn_payload(const OCTETSTRING &p_unsecured_gn_payload, OCTETSTRING &p_enc_gn_payload, params &p_params); + + int decrypt_gn_payload(const OCTETSTRING &p_enc_gn_payload, OCTETSTRING &p_unsecured_gn_payload, params &p_params); + + int sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, + const OCTETSTRING &p_private_key, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); + + const int get_protocol_version() const { return ProtocolVersion; }; + +private: + /*! + * \fn int process_ieee_1609_dot2_content(const Ieee1609Dot2::Ieee1609Dot2Content& p_ieee_1609_dot2_content, const bool p_verify, OCTETSTRING& + * p_unsecured_payload, params& p_params); \brief Verify and extract the unsecured payload from the Ieee1609Dot2::Ieee1609Dot2Content data structure + * \param[in] p_content The secured content to be processed + * \param[in] p_verify Set to true if security checks shall be applied + * \param[in] p_unsecured_payload The extracted payload + * \return 0 on success, negative value otherwise + */ + int process_ieee_1609_dot2_content(const Ieee1609Dot2::Ieee1609Dot2Content &p_ieee_1609_dot2_content, const bool p_verify, OCTETSTRING &p_unsecured_payload, + params &p_params); + int process_ieee_1609_dot2_signed_data(const Ieee1609Dot2::SignedData &p_signed_data, const bool p_verify, OCTETSTRING &p_unsecured_payload, + params &p_params); + int process_ieee_1609_dot2_encrypted_data(const Ieee1609Dot2::EncryptedData &p_encrypted_data, const bool p_verify, OCTETSTRING &p_unsecured_payload, + params &p_params); + int sign_tbs_data(const Ieee1609Dot2::ToBeSignedData &p_tbs_data, const Ieee1609Dot2BaseTypes::HashAlgorithm &p_hashAlgorithm, + Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); + + int hash_sha256(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data); + int hash_sha384(const OCTETSTRING &p_data, OCTETSTRING &p_hash_data); + int sign_ecdsa_nistp256(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); + int sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); + int sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, Ieee1609Dot2BaseTypes::Signature &p_signature, params &p_params); + int verify_sign_ecdsa_nistp256(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, const std::string &p_certificate_id, + params &p_params); + int verify_sign_ecdsa_brainpoolp256r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, const std::string &p_certificate_id, + params &p_params); + int verify_sign_ecdsa_brainpoolp384r1(const OCTETSTRING &p_hash, const Ieee1609Dot2BaseTypes::Signature &p_signature, const std::string &p_certificate_id, + params &p_params); + + int extract_verification_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_key_x, OCTETSTRING &p_public_key_y, + OCTETSTRING &p_public_comp_key, INTEGER &p_public_comp_key_mode); + int extract_encryption_keys(const Ieee1609Dot2::CertificateBase &p_cert, OCTETSTRING &p_public_enc_key_x, OCTETSTRING &p_public_enc_key_y, + OCTETSTRING &p_public_enc_comp_key, INTEGER &p_public_enc_comp_key_mode); + int extract_and_store_certificate(const Ieee1609Dot2::CertificateBase &p_certificate, std::string &p_certificate_id); +}; // End of class security_services diff --git a/ccsrc/Protocols/Security/sha256.cc b/ccsrc/Protocols/Security/sha256.cc index 7be5533028dddb6b1b59198128d5b8cf2ba9d834..dc8c7f5801f822a36a9ed5b1b11c66c62e1728c4 100644 --- a/ccsrc/Protocols/Security/sha256.cc +++ b/ccsrc/Protocols/Security/sha256.cc @@ -1,39 +1,39 @@ -/*! - * \file sha256.cc - * \brief Source file for SHA-256 helper methods. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include - -#include "sha256.hh" - -int sha256::generate(const OCTETSTRING& p_buffer, OCTETSTRING& p_hash) { - // Sanity check - if (p_buffer.lengthof() == 0) { - p_hash = get_sha256_empty_string(); - return 0; - } - - return generate(static_cast(p_buffer), p_buffer.lengthof(), p_hash); -} - -int sha256::generate(const unsigned char* p_buffer, const size_t p_length, OCTETSTRING& p_hash) { - // Sanity check - if ((p_buffer == nullptr) || (p_length == 0)) { - p_hash = get_sha256_empty_string(); - return 0; - } - - // Resize data buffer - p_hash = int2oct(0, SHA256_DIGEST_LENGTH); - // Compute the hash value - ::SHA256_Init(&_ctx); - ::SHA256_Update(&_ctx, p_buffer, p_length); - ::SHA256_Final((unsigned char*)static_cast(p_hash), &_ctx); - return 0; -}; +/*! + * \file sha256.cc + * \brief Source file for SHA-256 helper methods. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include + +#include "sha256.hh" + +int sha256::generate(const OCTETSTRING& p_buffer, OCTETSTRING& p_hash) { + // Sanity check + if (p_buffer.lengthof() == 0) { + p_hash = get_sha256_empty_string(); + return 0; + } + + return generate(static_cast(p_buffer), p_buffer.lengthof(), p_hash); +} + +int sha256::generate(const unsigned char* p_buffer, const size_t p_length, OCTETSTRING& p_hash) { + // Sanity check + if ((p_buffer == nullptr) || (p_length == 0)) { + p_hash = get_sha256_empty_string(); + return 0; + } + + // Resize data buffer + p_hash = int2oct(0, SHA256_DIGEST_LENGTH); + // Compute the hash value + ::SHA256_Init(&_ctx); + ::SHA256_Update(&_ctx, p_buffer, p_length); + ::SHA256_Final((unsigned char*)static_cast(p_hash), &_ctx); + return 0; +}; diff --git a/ccsrc/Protocols/Security/sha256.hh b/ccsrc/Protocols/Security/sha256.hh index 5cbde60fbf62d9d8f53f8ac49eedff60f01f480f..0de9a8890a4aff71ccdb2a4992b37d1c7c7e160a 100644 --- a/ccsrc/Protocols/Security/sha256.hh +++ b/ccsrc/Protocols/Security/sha256.hh @@ -1,66 +1,66 @@ -/*! - * \file sha256.hh - * \brief Header file for SHA-256 helper methods. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include - -class OCTETSTRING; //! TITAN forward declaration - -/*! - * \class sha256 - * \brief This class provides description of SHA-256 helper methods - */ -class sha256 { - SHA256_CTX _ctx; //! SHA context -public: - /*! - * \brief Default constructor - * Create a new instance of the sha256 class - */ - explicit sha256() : _ctx{} {}; - /*! - * \brief Default destructor - */ - virtual ~sha256(){}; - - /*! - * \fn int generate(const OCTETSTRING& p_buffer, OCTETSTRING& p_hash); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_buffer The data used to generate the SHA-256 hash - * \param[out] p_hash The SHA-256 hash value based of the provided data - * \return 0 on success, -1 otherwise - */ - int generate(const OCTETSTRING &p_buffer, OCTETSTRING &p_hash); - - /*! - * \fn int generate(const unsigned char* p_buffer, OCTETSTRING& p_hash); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_buffer The data used to generate the SHA-256 hash - * \param[in] The length of the data buffer - * \param[out] p_hash The SHA-256 hash value based of the provided data - * \return 0 on success, -1 otherwise - */ - int generate(const unsigned char *p_buffer, const size_t p_length, OCTETSTRING &p_hash); - - /*! - * \fn const OCTETSTRING get_sha256_empty_string() const; - * \brief Return the SHA-256 of an empty string - * \return The SHA-256 of an empty string - */ - inline const OCTETSTRING get_sha256_empty_string() const { - static unsigned char sha256_empty_string[] = { - 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, - 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}; //! SHA-256 of an empty string - return OCTETSTRING(32, sha256_empty_string); - }; - -}; // End of class sha256 +/*! + * \file sha256.hh + * \brief Header file for SHA-256 helper methods. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include + +class OCTETSTRING; //! TITAN forward declaration + +/*! + * \class sha256 + * \brief This class provides description of SHA-256 helper methods + */ +class sha256 { + SHA256_CTX _ctx; //! SHA context +public: + /*! + * \brief Default constructor + * Create a new instance of the sha256 class + */ + explicit sha256() : _ctx{} {}; + /*! + * \brief Default destructor + */ + virtual ~sha256(){}; + + /*! + * \fn int generate(const OCTETSTRING& p_buffer, OCTETSTRING& p_hash); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_buffer The data used to generate the SHA-256 hash + * \param[out] p_hash The SHA-256 hash value based of the provided data + * \return 0 on success, -1 otherwise + */ + int generate(const OCTETSTRING &p_buffer, OCTETSTRING &p_hash); + + /*! + * \fn int generate(const unsigned char* p_buffer, OCTETSTRING& p_hash); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_buffer The data used to generate the SHA-256 hash + * \param[in] The length of the data buffer + * \param[out] p_hash The SHA-256 hash value based of the provided data + * \return 0 on success, -1 otherwise + */ + int generate(const unsigned char *p_buffer, const size_t p_length, OCTETSTRING &p_hash); + + /*! + * \fn const OCTETSTRING get_sha256_empty_string() const; + * \brief Return the SHA-256 of an empty string + * \return The SHA-256 of an empty string + */ + inline const OCTETSTRING get_sha256_empty_string() const { + static unsigned char sha256_empty_string[] = { + 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, + 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55}; //! SHA-256 of an empty string + return OCTETSTRING(32, sha256_empty_string); + }; + +}; // End of class sha256 diff --git a/ccsrc/Protocols/Security/sha384.cc b/ccsrc/Protocols/Security/sha384.cc index 4102789fd0fa2f7177ef0b962d85dddc4c26d02c..285205101953307aec1e7623a34167b2b4d27cea 100644 --- a/ccsrc/Protocols/Security/sha384.cc +++ b/ccsrc/Protocols/Security/sha384.cc @@ -1,49 +1,49 @@ -/*! - * \file sha384.cc - * \brief Sorce file for SHA-384 helper methods. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#include - -#include - -#include "sha384.hh" - -int sha384::generate(const OCTETSTRING &p_buffer, OCTETSTRING &p_hash) { - // Sanity check - if (p_buffer.lengthof() == 0) { - p_hash = get_sha384_empty_string(); - return 0; - } - - return generate(static_cast(p_buffer), p_buffer.lengthof(), p_hash); -} - -int sha384::generate(const unsigned char *p_buffer, const size_t p_length, OCTETSTRING &p_hash) { - // Sanity check - if ((p_buffer == nullptr) || (p_length == 0)) { - p_hash = get_sha384_empty_string(); - return 0; - } - - // Resize data buffer - p_hash = int2oct(0, SHA384_DIGEST_LENGTH); - // Compute the hash value - ::SHA384_Init(&_ctx); - ::SHA384_Update(&_ctx, p_buffer, p_length); - ::SHA384_Final((unsigned char *)static_cast(p_hash), &_ctx); - return 0; -} - -const OCTETSTRING sha384::get_sha384_empty_string() const { - static unsigned char - sha384_empty_string[] = {0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, - 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, - 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b}; //! SHA-384 of an empty string - return OCTETSTRING(48, sha384_empty_string); -} +/*! + * \file sha384.cc + * \brief Sorce file for SHA-384 helper methods. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#include + +#include + +#include "sha384.hh" + +int sha384::generate(const OCTETSTRING &p_buffer, OCTETSTRING &p_hash) { + // Sanity check + if (p_buffer.lengthof() == 0) { + p_hash = get_sha384_empty_string(); + return 0; + } + + return generate(static_cast(p_buffer), p_buffer.lengthof(), p_hash); +} + +int sha384::generate(const unsigned char *p_buffer, const size_t p_length, OCTETSTRING &p_hash) { + // Sanity check + if ((p_buffer == nullptr) || (p_length == 0)) { + p_hash = get_sha384_empty_string(); + return 0; + } + + // Resize data buffer + p_hash = int2oct(0, SHA384_DIGEST_LENGTH); + // Compute the hash value + ::SHA384_Init(&_ctx); + ::SHA384_Update(&_ctx, p_buffer, p_length); + ::SHA384_Final((unsigned char *)static_cast(p_hash), &_ctx); + return 0; +} + +const OCTETSTRING sha384::get_sha384_empty_string() const { + static unsigned char + sha384_empty_string[] = {0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, + 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, + 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b}; //! SHA-384 of an empty string + return OCTETSTRING(48, sha384_empty_string); +} diff --git a/ccsrc/Protocols/Security/sha384.hh b/ccsrc/Protocols/Security/sha384.hh index 4d69d9ac376d41b6d3602dc4e82dfdb9d43af482..525763c73aeeea441e13595f355ac19b3ff1bf73 100644 --- a/ccsrc/Protocols/Security/sha384.hh +++ b/ccsrc/Protocols/Security/sha384.hh @@ -1,60 +1,60 @@ -/*! - * \file sha384.hh - * \brief Header file for SHA-384 helper methods. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include - -class OCTETSTRING; //! TITAN forward declaration - -/*! - * \class sha384 - * \brief This class provides description of SHA-384 helper methods - */ -class sha384 { - SHA512_CTX _ctx; //! SHA context -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the sha384 class - */ - explicit sha384() : _ctx{} {}; - /*! - * \brief Default destructor - */ - virtual ~sha384(){}; - - /*! - * \fn int generate(const OCTETSTRING& p_buffer, OCTETSTRING& p_hash); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_buffer The data used to generate the SHA-384 hash - * \param[out] p_hash The SHA-384 hash value based of the provided data - * \return 0 on success, -1 otherwise - */ - int generate(const OCTETSTRING &p_buffer, OCTETSTRING &p_hash); - - /*! - * \fn int generate(const OCTETSTRING p_buffer, OCTETSTRING& p_hash); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_buffer The data used to generate the SHA-384 hash - * \param[in] The length of the data buffer - * \param[out] p_hash The SHA-384 hash value based of the provided data - * \return 0 on success, -1 otherwise - */ - int generate(const unsigned char *p_buffer, const size_t p_length, OCTETSTRING &p_hash); - - /*! - * \fn const OCTETSTRING get_sha384_empty_string() const; - * \brief Return the SHA-384 of an empty string - * \return The SHA-384 of an empty string - */ - const OCTETSTRING get_sha384_empty_string() const; -}; // End of class sha384 +/*! + * \file sha384.hh + * \brief Header file for SHA-384 helper methods. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include + +class OCTETSTRING; //! TITAN forward declaration + +/*! + * \class sha384 + * \brief This class provides description of SHA-384 helper methods + */ +class sha384 { + SHA512_CTX _ctx; //! SHA context +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the sha384 class + */ + explicit sha384() : _ctx{} {}; + /*! + * \brief Default destructor + */ + virtual ~sha384(){}; + + /*! + * \fn int generate(const OCTETSTRING& p_buffer, OCTETSTRING& p_hash); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_buffer The data used to generate the SHA-384 hash + * \param[out] p_hash The SHA-384 hash value based of the provided data + * \return 0 on success, -1 otherwise + */ + int generate(const OCTETSTRING &p_buffer, OCTETSTRING &p_hash); + + /*! + * \fn int generate(const OCTETSTRING p_buffer, OCTETSTRING& p_hash); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_buffer The data used to generate the SHA-384 hash + * \param[in] The length of the data buffer + * \param[out] p_hash The SHA-384 hash value based of the provided data + * \return 0 on success, -1 otherwise + */ + int generate(const unsigned char *p_buffer, const size_t p_length, OCTETSTRING &p_hash); + + /*! + * \fn const OCTETSTRING get_sha384_empty_string() const; + * \brief Return the SHA-384 of an empty string + * \return The SHA-384 of an empty string + */ + const OCTETSTRING get_sha384_empty_string() const; +}; // End of class sha384 diff --git a/ccsrc/Protocols/SremSsem/SremCodec.cc b/ccsrc/Protocols/SremSsem/SremCodec.cc index e9aee034a44d03c381ffa295337995133730a77a..c3c59c99bb70d4507ec0fdfb04fde361c7a216ed 100644 --- a/ccsrc/Protocols/SremSsem/SremCodec.cc +++ b/ccsrc/Protocols/SremSsem/SremCodec.cc @@ -1,39 +1,39 @@ -#include "SremCodec.hh" -#include "LibItsSremSsem_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int SremCodec::encode(const SREM__PDU__Descriptions::SREM &srem, OCTETSTRING &data) { - loggers::get_instance().log(">>> SremCodec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(srem, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("SremCodec::encode: ", data); - } - return rc; -} - -int SremCodec::decode(const OCTETSTRING &data, SREM__PDU__Descriptions::SREM &srem, params *params) { - loggers::get_instance().log_msg(">>> SremCodec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), srem); - loggers::get_instance().log("SremCodec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("SremCodec::decode: ", srem); - } - return rc; -} - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_SREM; -} - -int SremPDUCodec::encode(const SREM__PDU__Descriptions::SREM &p_srem, BITSTRING &p_data) { - return _encode(SREM__PDU__Descriptions::SREM_descr_, asn_DEF_SREM, p_srem, p_data); -} - -int SremPDUCodec::decode(const BITSTRING &p_data, SREM__PDU__Descriptions::SREM &p_srem) { - return _decode(SREM__PDU__Descriptions::SREM_descr_, asn_DEF_SREM, p_data, p_srem); -} +#include "SremCodec.hh" +#include "LibItsSremSsem_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int SremCodec::encode(const SREM__PDU__Descriptions::SREM &srem, OCTETSTRING &data) { + loggers::get_instance().log(">>> SremCodec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(srem, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("SremCodec::encode: ", data); + } + return rc; +} + +int SremCodec::decode(const OCTETSTRING &data, SREM__PDU__Descriptions::SREM &srem, params *params) { + loggers::get_instance().log_msg(">>> SremCodec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), srem); + loggers::get_instance().log("SremCodec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("SremCodec::decode: ", srem); + } + return rc; +} + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_SREM; +} + +int SremPDUCodec::encode(const SREM__PDU__Descriptions::SREM &p_srem, BITSTRING &p_data) { + return _encode(SREM__PDU__Descriptions::SREM_descr_, asn_DEF_SREM, p_srem, p_data); +} + +int SremPDUCodec::decode(const BITSTRING &p_data, SREM__PDU__Descriptions::SREM &p_srem) { + return _decode(SREM__PDU__Descriptions::SREM_descr_, asn_DEF_SREM, p_data, p_srem); +} diff --git a/ccsrc/Protocols/SremSsem/SremCodec.hh b/ccsrc/Protocols/SremSsem/SremCodec.hh index a2be0eb9631d9617936703bf1a4fa797cab14516..7e6b02c2b1223c0ef9b6e1cc9509efedee6376d7 100644 --- a/ccsrc/Protocols/SremSsem/SremCodec.hh +++ b/ccsrc/Protocols/SremSsem/SremCodec.hh @@ -1,28 +1,28 @@ -#ifndef SREMCODEC_H -#define SREMCODEC_H - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -#include "LibItsSremSsem_TestSystem.hh" - -class SremPDUCodec : public per_codec { -public: - SremPDUCodec(){}; - virtual int encode(const SREM__PDU__Descriptions::SREM &srem, BITSTRING &data); - virtual int decode(const BITSTRING &data, SREM__PDU__Descriptions::SREM &); -}; - -class SremCodec : public codec { - SremPDUCodec asn_codec; - -public: - SremCodec() : codec(), asn_codec(){}; - virtual ~SremCodec(){}; - - virtual int encode(const SREM__PDU__Descriptions::SREM &srem, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, SREM__PDU__Descriptions::SREM &, params *params = NULL); -}; - -#endif +#ifndef SREMCODEC_H +#define SREMCODEC_H + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +#include "LibItsSremSsem_TestSystem.hh" + +class SremPDUCodec : public per_codec { +public: + SremPDUCodec(){}; + virtual int encode(const SREM__PDU__Descriptions::SREM &srem, BITSTRING &data); + virtual int decode(const BITSTRING &data, SREM__PDU__Descriptions::SREM &); +}; + +class SremCodec : public codec { + SremPDUCodec asn_codec; + +public: + SremCodec() : codec(), asn_codec(){}; + virtual ~SremCodec(){}; + + virtual int encode(const SREM__PDU__Descriptions::SREM &srem, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, SREM__PDU__Descriptions::SREM &, params *params = NULL); +}; + +#endif diff --git a/ccsrc/Protocols/SremSsem/SremSsemLayer.cc b/ccsrc/Protocols/SremSsem/SremSsemLayer.cc index a3504a0ace0636a3e136905159939ffccba728aa..acda88aa6929bba955d6ccea329ef06292b420cc 100644 --- a/ccsrc/Protocols/SremSsem/SremSsemLayer.cc +++ b/ccsrc/Protocols/SremSsem/SremSsemLayer.cc @@ -20,7 +20,7 @@ SremSsemLayer::SremSsemLayer(const std::string &p_type, const std::string ¶m registration::get_instance().add_item(p_type, this); } -void SremSsemLayer::sendMsg(const LibItsSremSsem__TestSystem::SremReq &p, params ¶ms) { +void SremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::SremReq &p, params ¶ms) { loggers::get_instance().log_msg(">>> SremSsemLayer::sendMsg: ", p); // Encode srem PDU @@ -34,7 +34,7 @@ void SremSsemLayer::sendMsg(const LibItsSremSsem__TestSystem::SremReq &p, params send_data(data, _params); } -void SremSsemLayer::sendMsg(const LibItsSremSsem__TestSystem::SsemReq &p, params ¶ms) { +void SremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::SsemReq &p, params ¶ms) { loggers::get_instance().log_msg(">>> SremSsemLayer::sendMsg: ", p); // Encode ssem PDU @@ -59,7 +59,7 @@ void SremSsemLayer::receive_data(OCTETSTRING &data, params ¶ms) { // Sanity check if (*(static_cast(data) + 1) == 0x09) { // Check that received packet has SRE message id // Decode the SREM payload - LibItsSremSsem__TestSystem::SremInd p; + LibItsSremSsem__TypesAndValues::SremInd p; _srem_codec.decode(data, p.msgIn()); if (!p.msgIn().is_bound()) { // Discard it @@ -142,7 +142,7 @@ void SremSsemLayer::receive_data(OCTETSTRING &data, params ¶ms) { to_all_upper_ports(p, params); } else if (*(static_cast(data) + 1) == 0x0A) { // Check that received packet has SSE message id // Decode the SSEM payload - LibItsSremSsem__TestSystem::SsemInd p; + LibItsSremSsem__TypesAndValues::SsemInd p; _ssem_codec.decode(data, p.msgIn()); if (!p.msgIn().is_bound()) { // Discard it diff --git a/ccsrc/Protocols/SremSsem/SremSsemLayer.hh b/ccsrc/Protocols/SremSsem/SremSsemLayer.hh index 9b0b7503d37987df988f9417698c7fdfc4e9c1bd..a323d1f8fae95bff980482446c1fd1424f3fb771 100644 --- a/ccsrc/Protocols/SremSsem/SremSsemLayer.hh +++ b/ccsrc/Protocols/SremSsem/SremSsemLayer.hh @@ -32,8 +32,8 @@ public: SremSsemLayer(const std::string &p_type, const std::string ¶m); virtual ~SremSsemLayer(){}; - void sendMsg(const LibItsSremSsem__TestSystem::SremReq &, params ¶ms); - void sendMsg(const LibItsSremSsem__TestSystem::SsemReq &, params ¶ms); + void sendMsg(const LibItsSremSsem__TypesAndValues::SremReq &, params ¶ms); + void sendMsg(const LibItsSremSsem__TypesAndValues::SsemReq &, params ¶ms); virtual void send_data(OCTETSTRING &data, params ¶ms); virtual void receive_data(OCTETSTRING &data, params &info); diff --git a/ccsrc/Protocols/SremSsem/SremSsemLayerFactory.hh b/ccsrc/Protocols/SremSsem/SremSsemLayerFactory.hh index 34df220a9db9afa1d69f372e170e4683dedd4eff..70994370df10015b87ad6df341a1eeb6102640bd 100644 --- a/ccsrc/Protocols/SremSsem/SremSsemLayerFactory.hh +++ b/ccsrc/Protocols/SremSsem/SremSsemLayerFactory.hh @@ -1,26 +1,26 @@ -/*! - * \file SremSsemLayerFactory.hh - * \brief Header file for ITS SremSsem protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "SremSsemLayer.hh" - -class SremSsemLayerFactory : public layer_factory { - static SremSsemLayerFactory _f; - -public: - SremSsemLayerFactory() { - // Register factory - layer_stack_builder::register_layer_factory("SremSsem", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new SremSsemLayer(p_type, p_param); }; -}; // End of class SremSsemLayerFactory +/*! + * \file SremSsemLayerFactory.hh + * \brief Header file for ITS SremSsem protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "SremSsemLayer.hh" + +class SremSsemLayerFactory : public layer_factory { + static SremSsemLayerFactory _f; + +public: + SremSsemLayerFactory() { + // Register factory + layer_stack_builder::register_layer_factory("SremSsem", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new SremSsemLayer(p_type, p_param); }; +}; // End of class SremSsemLayerFactory diff --git a/ccsrc/Protocols/SremSsem/SremSsemTypes.hh b/ccsrc/Protocols/SremSsem/SremSsemTypes.hh index a97d40cc3342767506a47119b893fb192ad0391a..3197ec6e6a97d4c4ce19e49cf81a41db8845af38 100644 --- a/ccsrc/Protocols/SremSsem/SremSsemTypes.hh +++ b/ccsrc/Protocols/SremSsem/SremSsemTypes.hh @@ -1,8 +1,8 @@ -#ifndef SREMSSEMTYPES_H -#define SREMSSEMTYPES_H - -using namespace std; // Required for isnan() -#include "LibItsSremSsem_TestSystem.hh" -#include "LibItsSremSsem_TypesAndValues.hh" - -#endif +#ifndef SREMSSEMTYPES_H +#define SREMSSEMTYPES_H + +using namespace std; // Required for isnan() +#include "LibItsSremSsem_TestSystem.hh" +#include "LibItsSremSsem_TypesAndValues.hh" + +#endif diff --git a/ccsrc/Protocols/SremSsem/SsemCodec.cc b/ccsrc/Protocols/SremSsem/SsemCodec.cc index e92c0ee47931b65c2d945092d32b403eb5e26879..d46e0fe3eed1e40102894d3cd5d8ac3843516b19 100644 --- a/ccsrc/Protocols/SremSsem/SsemCodec.cc +++ b/ccsrc/Protocols/SremSsem/SsemCodec.cc @@ -1,39 +1,39 @@ -#include "SsemCodec.hh" -#include "LibItsSremSsem_TestSystem.hh" -#include "asn1/asn_application.h" // from asn1c -#include "loggers.hh" - -int SsemCodec::encode(const SSEM__PDU__Descriptions::SSEM &ssem, OCTETSTRING &data) { - loggers::get_instance().log(">>> SsemCodec::encode"); - - BITSTRING b; - int rc = asn_codec.encode(ssem, b); - if (rc) { - data = bit2oct(b); - loggers::get_instance().log_msg("SsemCodec::encode: ", data); - } - return rc; -} - -int SsemCodec::decode(const OCTETSTRING &data, SSEM__PDU__Descriptions::SSEM &ssem, params *params) { - loggers::get_instance().log_msg(">>> SsemCodec::decode: ", data); - - int rc = asn_codec.decode(oct2bit(data), ssem); - loggers::get_instance().log("SsemCodec::decode: ASN.1 codec returned %d", rc); - if (rc) { - loggers::get_instance().log_msg("SsemCodec::decode: ", ssem); - } - return rc; -} - -extern "C" { -extern asn_TYPE_descriptor_t asn_DEF_SSEM; -} - -int SsemPDUCodec::encode(const SSEM__PDU__Descriptions::SSEM &p_ssem, BITSTRING &p_data) { - return _encode(SSEM__PDU__Descriptions::SSEM_descr_, asn_DEF_SSEM, p_ssem, p_data); -} - -int SsemPDUCodec::decode(const BITSTRING &p_data, SSEM__PDU__Descriptions::SSEM &p_ssem) { - return _decode(SSEM__PDU__Descriptions::SSEM_descr_, asn_DEF_SSEM, p_data, p_ssem); -} +#include "SsemCodec.hh" +#include "LibItsSremSsem_TestSystem.hh" +#include "asn1/asn_application.h" // from asn1c +#include "loggers.hh" + +int SsemCodec::encode(const SSEM__PDU__Descriptions::SSEM &ssem, OCTETSTRING &data) { + loggers::get_instance().log(">>> SsemCodec::encode"); + + BITSTRING b; + int rc = asn_codec.encode(ssem, b); + if (rc) { + data = bit2oct(b); + loggers::get_instance().log_msg("SsemCodec::encode: ", data); + } + return rc; +} + +int SsemCodec::decode(const OCTETSTRING &data, SSEM__PDU__Descriptions::SSEM &ssem, params *params) { + loggers::get_instance().log_msg(">>> SsemCodec::decode: ", data); + + int rc = asn_codec.decode(oct2bit(data), ssem); + loggers::get_instance().log("SsemCodec::decode: ASN.1 codec returned %d", rc); + if (rc) { + loggers::get_instance().log_msg("SsemCodec::decode: ", ssem); + } + return rc; +} + +extern "C" { +extern asn_TYPE_descriptor_t asn_DEF_SSEM; +} + +int SsemPDUCodec::encode(const SSEM__PDU__Descriptions::SSEM &p_ssem, BITSTRING &p_data) { + return _encode(SSEM__PDU__Descriptions::SSEM_descr_, asn_DEF_SSEM, p_ssem, p_data); +} + +int SsemPDUCodec::decode(const BITSTRING &p_data, SSEM__PDU__Descriptions::SSEM &p_ssem) { + return _decode(SSEM__PDU__Descriptions::SSEM_descr_, asn_DEF_SSEM, p_data, p_ssem); +} diff --git a/ccsrc/Protocols/SremSsem/SsemCodec.hh b/ccsrc/Protocols/SremSsem/SsemCodec.hh index 02b109249f807f9d20c058f0b7d45f599b9dea8d..c0292a83af23f26c4c738285d9c8b71cd840f813 100644 --- a/ccsrc/Protocols/SremSsem/SsemCodec.hh +++ b/ccsrc/Protocols/SremSsem/SsemCodec.hh @@ -1,28 +1,28 @@ -#ifndef SSEMCODEC_H -#define SSEMCODEC_H - -#include "codec.hh" -#include "params.hh" -#include "per_codec.hh" - -#include "LibItsSremSsem_TestSystem.hh" - -class SsemPDUCodec : public per_codec { -public: - SsemPDUCodec(){}; - virtual int encode(const SSEM__PDU__Descriptions::SSEM &ssem, BITSTRING &data); - virtual int decode(const BITSTRING &data, SSEM__PDU__Descriptions::SSEM &); -}; - -class SsemCodec : public codec { - SsemPDUCodec asn_codec; - -public: - SsemCodec() : codec(), asn_codec(){}; - virtual ~SsemCodec(){}; - - virtual int encode(const SSEM__PDU__Descriptions::SSEM &ssem, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, SSEM__PDU__Descriptions::SSEM &, params *params = NULL); -}; - -#endif +#ifndef SSEMCODEC_H +#define SSEMCODEC_H + +#include "codec.hh" +#include "params.hh" +#include "per_codec.hh" + +#include "LibItsSremSsem_TestSystem.hh" + +class SsemPDUCodec : public per_codec { +public: + SsemPDUCodec(){}; + virtual int encode(const SSEM__PDU__Descriptions::SSEM &ssem, BITSTRING &data); + virtual int decode(const BITSTRING &data, SSEM__PDU__Descriptions::SSEM &); +}; + +class SsemCodec : public codec { + SsemPDUCodec asn_codec; + +public: + SsemCodec() : codec(), asn_codec(){}; + virtual ~SsemCodec(){}; + + virtual int encode(const SSEM__PDU__Descriptions::SSEM &ssem, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, SSEM__PDU__Descriptions::SSEM &, params *params = NULL); +}; + +#endif diff --git a/ccsrc/Protocols/SremSsem/module.mk b/ccsrc/Protocols/SremSsem/module.mk index b43f0e026e1ca4fe2a00c8b2756013cf1c26ad74..1203c69cbd1de3989b60c61f131cce3927c8df81 100644 --- a/ccsrc/Protocols/SremSsem/module.mk +++ b/ccsrc/Protocols/SremSsem/module.mk @@ -1,3 +1,3 @@ -sources := SremCodec.cc SremSsemLayer.cc SsemCodec.cc -includes := . - +sources := SremCodec.cc SremSsemLayer.cc SsemCodec.cc +includes := . + diff --git a/ccsrc/Protocols/Tcp/module.mk b/ccsrc/Protocols/Tcp/module.mk index 0b8478fdc5709b858cd7d36b73918af4f49fb849..44d6c5606d15d682d68a77c6c5c15a72b0ba3b45 100644 --- a/ccsrc/Protocols/Tcp/module.mk +++ b/ccsrc/Protocols/Tcp/module.mk @@ -1,3 +1,3 @@ -sources := tcp_layer.cc -includes := . - +sources := tcp_layer.cc +includes := . + diff --git a/ccsrc/Protocols/Tcp/tcp_layer.cc b/ccsrc/Protocols/Tcp/tcp_layer.cc index 5a53c1b4c2a7ee4eea48cde36838292ab76e8e2e..7214a11a756dd73cfd4d5ad95df5dbd22964661a 100644 --- a/ccsrc/Protocols/Tcp/tcp_layer.cc +++ b/ccsrc/Protocols/Tcp/tcp_layer.cc @@ -1,243 +1,243 @@ -#include -#include -#include -#include -#include - -#include "tcp_layer_factory.hh" - -#include "loggers.hh" - -tcp_layer::tcp_layer(const std::string & p_type, const std::string & param) : layer(p_type), SSL_Socket(), PORT(p_type.c_str()), _params(), _client_id{-1}, _time_key("tcp_layer::Handle_Fd_Event_Readable"), _reconnect_on_send{false} { - loggers::get_instance().log(">>> tcp_layer::tcp_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - _params.log(); - - set_socket_debugging(false); - params::const_iterator it = _params.find(params::debug); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("debug"), "0")); - } else if (it->second.compare("1") == 0) { - set_socket_debugging(true); - } - it = _params.find(std::string("tcp_fragmented")); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("tcp_fragmented"), "0")); - } - bool server_mode = false; - it = _params.find(params::server_mode); - if (it != _params.cend()) { - server_mode = (1 == std::stoi(it->second)); - } else { - _params.insert(std::pair(std::string("server_mode"), "0")); - } - it = _params.find(params::server); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("server"), "127.0.0.1")); // TODO Try using params::server instead of std::string("server") - } - if (!parameter_set(params::server.c_str(), _params[params::server].c_str())) { - loggers::get_instance().warning("tcp_layer::set_parameter: Unprocessed parameter: %s", params::server.c_str()); - } - bool ssl_mode = false; - it = _params.find(params::use_ssl); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("use_ssl"), "0")); - } else if (it->second.compare("1") == 0) { - _params.insert(std::pair(std::string("use_ssl"), "1")); - ssl_mode = true; - } - set_ssl_use_ssl(ssl_mode); - it = _params.find(params::port); - if (it == _params.cend()) { - if (_params[params::use_ssl].compare("0") == 0) { // Use standard HTTP port - _params.insert(std::pair(std::string("port"), "80")); - } else { // Use standard HTTPS port - _params.insert(std::pair(std::string("port"), "443")); - } - } - if (!parameter_set(remote_port_name(), _params[params::port].c_str())) { - loggers::get_instance().warning("tcp_layer::set_parameter: Unprocessed parameter: %s", params::port.c_str()); - } - it = _params.find(params::local_port); - if (it == _params.cend()) { - if (_params[params::use_ssl].compare("0") == 0) { // Use standard HTTP local_port - _params.insert(std::pair(std::string("local_port"), "80")); - } else { // Use standard HTTPS local_port - _params.insert(std::pair(std::string("local_port"), "443")); - } - } - if (!parameter_set(local_port_name(), _params[params::local_port].c_str())) { - loggers::get_instance().warning("tcp_layer::set_parameter: Unprocessed parameter: %s", params::local_port.c_str()); - } - - parameter_set(use_connection_ASPs_name(), (!server_mode) ? "yes" : "no"); - parameter_set(server_backlog_name(), "1024"); - loggers::get_instance().log("tcp_layer::tcp_layer: server_mode=%x", server_mode); - set_server_mode(server_mode); - if (server_mode) { - parameter_set("serverPort", _params[params::local_port].c_str()); - } - if (ssl_mode) { // Add certificate bundle - // Check mutual authentication param - _params.insert(std::pair(std::string("mutual_tls"), "0")); - parameter_set(ssl_verifycertificate_name(), "no"); - it = _params.find(params::mutual_auth); - if (it == _params.cend()) { - if (_params[params::mutual_auth].compare("1") == 0) { // Use mutual authentication - parameter_set(ssl_verifycertificate_name(), "yes"); - _params.insert(std::pair(std::string("mutual_tls"), "1")); - } - } - // Set trusted CA file - it = _params.find(params::mutual_auth); - if (it == _params.cend()) { - parameter_set(ssl_trustedCAlist_file_name(), it->second.c_str()); - _params.insert(std::pair(std::string("mutual_tls"), it->second)); - } else { - parameter_set(ssl_trustedCAlist_file_name(), "/usr/share/ca-certificates/mozilla/Amazon_Root_CA_1.crt"); - } - // Set additional certificates - //parameter_set(ssl_private_key_file_name(), "../certificates/out/privates/e5e11abad8003766e4a7b721afb175a189b5f4cc7046af9b0d8eaebb86f28c40_server_dsa.key.pem"); - //parameter_set(ssl_certificate_file_name(), "../certificates/out/certs/e5e11abad8003766e4a7b721afb175a189b5f4cc7046af9b0d8eaebb86f28c40_server_dsa.cert.pem"); - } - set_ttcn_buffer_usercontrol(false); - set_handle_half_close(true); - - map_user(); - - parameter_set(client_TCP_reconnect_name(), "yes"); - - if (server_mode == 0) { - loggers::get_instance().log("tcp_layer::tcp_layer: Establish connection: %s/%s", _params[params::server].c_str(), _params[params::port].c_str()); - open_client_connection(_params[params::server].c_str(), _params[params::port].c_str(), NULL, NULL); - } - } - -tcp_layer::~tcp_layer() { - loggers::get_instance().log(">>> tcp_layer::~tcp_layer: %d", _client_id); - if (_client_id != -1) { - remove_client(_client_id); - } - - unmap_user(); -} - -void tcp_layer::Handle_Fd_Event(int fd, boolean is_readable, boolean is_writable, boolean is_error) -{ - loggers::get_instance().log(">>> tcp_layer::Handle_Fd_Event: %d", fd); - Handle_Socket_Event(fd, is_readable, is_writable, is_error); - log_debug("<<< tcp_layer::Handle_Fd_Event"); -} - -void tcp_layer::Handle_Timeout(double time_since_last_call) -{ - loggers::get_instance().log(">>> tcp_layer::Handle_Timeout: %f", time_since_last_call); - Handle_Timeout_Event(time_since_last_call); - loggers::get_instance().log("<<< tcp_layer::Handle_Timeout"); -} - -void tcp_layer::send_data(OCTETSTRING& data, params& params) { - loggers::get_instance().log_msg(">>> tcp_layer::send_data: ", data); - - loggers::get_instance().log("tcp_layer::send_data: SSL mode: %x", get_ssl_use_ssl()); - loggers::get_instance().log("tcp_layer::send_data: server_mode: %s", _params[params::server_mode].c_str()); - loggers::get_instance().log("tcp_layer::send_data: peer_list_get_nr_of_peers: %d", peer_list_get_nr_of_peers()); - - if ((_params[params::server_mode].compare("0") == 0) && (peer_list_get_nr_of_peers() == 0)) { - // Reconnect (e.g. HTTP connection lost - loggers::get_instance().log("tcp_layer::send_data: Re-establish connection: %s/%s", _params[params::server].c_str(), _params[params::port].c_str()); - open_client_connection(_params[params::server].c_str(), _params[params::port].c_str(), NULL, NULL); - } - send_outgoing(static_cast(data), data.lengthof(), _client_id); -} - -void tcp_layer::receive_data(OCTETSTRING& data, params& params) { - loggers::get_instance().log_msg(">>> tcp_layer::receive_data: ", data); - - receive_to_all_layers(data, params); -} - -void tcp_layer::message_incoming(const unsigned char* message_buffer, int length, int client_id) { - loggers::get_instance().log(">>> tcp_layer::message_incoming"); - loggers::get_instance().log_to_hexa("tcp_layer::message_incoming: ", message_buffer, length); - - - float duration; - loggers::get_instance().set_start_time(_time_key); - OCTETSTRING data(length, message_buffer); - params params; - this->receive_data(data, params); // TODO Check execution time for decoding operation - loggers::get_instance().set_stop_time(_time_key, duration); -} - -void tcp_layer::client_connection_opened(int p_client_id) -{ - loggers::get_instance().log(">>> tcp_layer::client_connection_opened: %d", p_client_id); - _client_id = p_client_id; -} - -bool tcp_layer::add_user_data(int p_client_id) -{ - loggers::get_instance().log(">>> tcp_layer::add_user_data: %d", p_client_id); - if (_params[params::use_ssl].compare("0") == 0) { - loggers::get_instance().log("tcp_layer::add_user_data: Non secured mode"); - return Abstract_Socket::add_user_data(p_client_id); - } - loggers::get_instance().log("tcp_layer::add_user_data: SSL mode"); - return SSL_Socket::add_user_data(p_client_id); -} - -int tcp_layer::send_message_on_fd(int p_client_id, const unsigned char * message_buffer, int length_of_message) -{ - loggers::get_instance().log(">>> tcp_layer::send_message_on_fd: %d", p_client_id); - - if(get_user_data(p_client_id)) { - loggers::get_instance().log("tcp_layer::send_message_on_fd: SSL mode"); - return SSL_Socket::send_message_on_fd(p_client_id, message_buffer, length_of_message); - } - - loggers::get_instance().log("tcp_layer::send_message_on_fd: Non secured mode"); - return Abstract_Socket::send_message_on_fd(p_client_id, message_buffer, length_of_message); -} - -int tcp_layer::send_message_on_nonblocking_fd(int p_client_id, const unsigned char * message_buffer, int length_of_message) -{ - loggers::get_instance().log(">>> tcp_layer::send_message_on_nonblocking_fd: %d", p_client_id); - - if(get_user_data(p_client_id)) { - loggers::get_instance().log("tcp_layer::send_message_on_nonblocking_fd: SSL mode"); - return SSL_Socket::send_message_on_nonblocking_fd(p_client_id, message_buffer, length_of_message); - } - - loggers::get_instance().log("tcp_layer::send_message_on_nonblocking_fd: Non secured mode"); - return Abstract_Socket::send_message_on_nonblocking_fd(p_client_id, message_buffer, length_of_message); -} - -int tcp_layer::receive_message_on_fd(int p_client_id) -{ - loggers::get_instance().log(">>> tcp_layer::receive_message_on_fd: %d", p_client_id); - - if(get_user_data(p_client_id)) { - // INFO: it is assumed that only SSL_Socket assigns user data to each peer - loggers::get_instance().log("tcp_layer::receive_message_on_fd: SSL mode"); - return SSL_Socket::receive_message_on_fd(p_client_id); - } - - loggers::get_instance().log("tcp_layer::receive_message_on_fd: Non secured mode"); - if (_params[std::string("tcp_fragmented")].compare("1") == 0) { - sleep(5); // FIXME When HTTP paquet is fragmented into several TCP packets, a timer is required. This is a Q&D solution - } - return Abstract_Socket::receive_message_on_fd(p_client_id); -} - -void tcp_layer::peer_disconnected(int p_client_id) -{ - loggers::get_instance().log(">>> tcp_layer::peer_disconnected: %d", p_client_id); - - Abstract_Socket::peer_disconnected(p_client_id); - _client_id = -1; -} - -tcp_layer_factory tcp_layer_factory::_f; - +#include +#include +#include +#include +#include + +#include "tcp_layer_factory.hh" + +#include "loggers.hh" + +tcp_layer::tcp_layer(const std::string & p_type, const std::string & param) : layer(p_type), SSL_Socket(), PORT(p_type.c_str()), _params(), _client_id{-1}, _time_key("tcp_layer::Handle_Fd_Event_Readable"), _reconnect_on_send{false} { + loggers::get_instance().log(">>> tcp_layer::tcp_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + _params.log(); + + set_socket_debugging(false); + params::const_iterator it = _params.find(params::debug); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("debug"), "0")); + } else if (it->second.compare("1") == 0) { + set_socket_debugging(true); + } + it = _params.find(std::string("tcp_fragmented")); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("tcp_fragmented"), "0")); + } + bool server_mode = false; + it = _params.find(params::server_mode); + if (it != _params.cend()) { + server_mode = (1 == std::stoi(it->second)); + } else { + _params.insert(std::pair(std::string("server_mode"), "0")); + } + it = _params.find(params::server); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("server"), "127.0.0.1")); // TODO Try using params::server instead of std::string("server") + } + if (!parameter_set(params::server.c_str(), _params[params::server].c_str())) { + loggers::get_instance().warning("tcp_layer::set_parameter: Unprocessed parameter: %s", params::server.c_str()); + } + bool ssl_mode = false; + it = _params.find(params::use_ssl); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("use_ssl"), "0")); + } else if (it->second.compare("1") == 0) { + _params.insert(std::pair(std::string("use_ssl"), "1")); + ssl_mode = true; + } + set_ssl_use_ssl(ssl_mode); + it = _params.find(params::port); + if (it == _params.cend()) { + if (_params[params::use_ssl].compare("0") == 0) { // Use standard HTTP port + _params.insert(std::pair(std::string("port"), "80")); + } else { // Use standard HTTPS port + _params.insert(std::pair(std::string("port"), "443")); + } + } + if (!parameter_set(remote_port_name(), _params[params::port].c_str())) { + loggers::get_instance().warning("tcp_layer::set_parameter: Unprocessed parameter: %s", params::port.c_str()); + } + it = _params.find(params::local_port); + if (it == _params.cend()) { + if (_params[params::use_ssl].compare("0") == 0) { // Use standard HTTP local_port + _params.insert(std::pair(std::string("local_port"), "80")); + } else { // Use standard HTTPS local_port + _params.insert(std::pair(std::string("local_port"), "443")); + } + } + if (!parameter_set(local_port_name(), _params[params::local_port].c_str())) { + loggers::get_instance().warning("tcp_layer::set_parameter: Unprocessed parameter: %s", params::local_port.c_str()); + } + + parameter_set(use_connection_ASPs_name(), (!server_mode) ? "yes" : "no"); + parameter_set(server_backlog_name(), "1024"); + loggers::get_instance().log("tcp_layer::tcp_layer: server_mode=%x", server_mode); + set_server_mode(server_mode); + if (server_mode) { + parameter_set("serverPort", _params[params::local_port].c_str()); + } + if (ssl_mode) { // Add certificate bundle + // Check mutual authentication param + _params.insert(std::pair(std::string("mutual_tls"), "0")); + parameter_set(ssl_verifycertificate_name(), "no"); + it = _params.find(params::mutual_auth); + if (it == _params.cend()) { + if (_params[params::mutual_auth].compare("1") == 0) { // Use mutual authentication + parameter_set(ssl_verifycertificate_name(), "yes"); + _params.insert(std::pair(std::string("mutual_tls"), "1")); + } + } + // Set trusted CA file + it = _params.find(params::mutual_auth); + if (it == _params.cend()) { + parameter_set(ssl_trustedCAlist_file_name(), it->second.c_str()); + _params.insert(std::pair(std::string("mutual_tls"), it->second)); + } else { + parameter_set(ssl_trustedCAlist_file_name(), "/usr/share/ca-certificates/mozilla/Amazon_Root_CA_1.crt"); + } + // Set additional certificates + //parameter_set(ssl_private_key_file_name(), "../certificates/out/privates/e5e11abad8003766e4a7b721afb175a189b5f4cc7046af9b0d8eaebb86f28c40_server_dsa.key.pem"); + //parameter_set(ssl_certificate_file_name(), "../certificates/out/certs/e5e11abad8003766e4a7b721afb175a189b5f4cc7046af9b0d8eaebb86f28c40_server_dsa.cert.pem"); + } + set_ttcn_buffer_usercontrol(false); + set_handle_half_close(true); + + map_user(); + + parameter_set(client_TCP_reconnect_name(), "yes"); + + if (server_mode == 0) { + loggers::get_instance().log("tcp_layer::tcp_layer: Establish connection: %s/%s", _params[params::server].c_str(), _params[params::port].c_str()); + open_client_connection(_params[params::server].c_str(), _params[params::port].c_str(), NULL, NULL); + } + } + +tcp_layer::~tcp_layer() { + loggers::get_instance().log(">>> tcp_layer::~tcp_layer: %d", _client_id); + if (_client_id != -1) { + remove_client(_client_id); + } + + unmap_user(); +} + +void tcp_layer::Handle_Fd_Event(int fd, boolean is_readable, boolean is_writable, boolean is_error) +{ + loggers::get_instance().log(">>> tcp_layer::Handle_Fd_Event: %d", fd); + Handle_Socket_Event(fd, is_readable, is_writable, is_error); + log_debug("<<< tcp_layer::Handle_Fd_Event"); +} + +void tcp_layer::Handle_Timeout(double time_since_last_call) +{ + loggers::get_instance().log(">>> tcp_layer::Handle_Timeout: %f", time_since_last_call); + Handle_Timeout_Event(time_since_last_call); + loggers::get_instance().log("<<< tcp_layer::Handle_Timeout"); +} + +void tcp_layer::send_data(OCTETSTRING& data, params& params) { + loggers::get_instance().log_msg(">>> tcp_layer::send_data: ", data); + + loggers::get_instance().log("tcp_layer::send_data: SSL mode: %x", get_ssl_use_ssl()); + loggers::get_instance().log("tcp_layer::send_data: server_mode: %s", _params[params::server_mode].c_str()); + loggers::get_instance().log("tcp_layer::send_data: peer_list_get_nr_of_peers: %d", peer_list_get_nr_of_peers()); + + if ((_params[params::server_mode].compare("0") == 0) && (peer_list_get_nr_of_peers() == 0)) { + // Reconnect (e.g. HTTP connection lost + loggers::get_instance().log("tcp_layer::send_data: Re-establish connection: %s/%s", _params[params::server].c_str(), _params[params::port].c_str()); + open_client_connection(_params[params::server].c_str(), _params[params::port].c_str(), NULL, NULL); + } + send_outgoing(static_cast(data), data.lengthof(), _client_id); +} + +void tcp_layer::receive_data(OCTETSTRING& data, params& params) { + loggers::get_instance().log_msg(">>> tcp_layer::receive_data: ", data); + + receive_to_all_layers(data, params); +} + +void tcp_layer::message_incoming(const unsigned char* message_buffer, int length, int client_id) { + loggers::get_instance().log(">>> tcp_layer::message_incoming"); + loggers::get_instance().log_to_hexa("tcp_layer::message_incoming: ", message_buffer, length); + + + float duration; + loggers::get_instance().set_start_time(_time_key); + OCTETSTRING data(length, message_buffer); + params params; + this->receive_data(data, params); // TODO Check execution time for decoding operation + loggers::get_instance().set_stop_time(_time_key, duration); +} + +void tcp_layer::client_connection_opened(int p_client_id) +{ + loggers::get_instance().log(">>> tcp_layer::client_connection_opened: %d", p_client_id); + _client_id = p_client_id; +} + +bool tcp_layer::add_user_data(int p_client_id) +{ + loggers::get_instance().log(">>> tcp_layer::add_user_data: %d", p_client_id); + if (_params[params::use_ssl].compare("0") == 0) { + loggers::get_instance().log("tcp_layer::add_user_data: Non secured mode"); + return Abstract_Socket::add_user_data(p_client_id); + } + loggers::get_instance().log("tcp_layer::add_user_data: SSL mode"); + return SSL_Socket::add_user_data(p_client_id); +} + +int tcp_layer::send_message_on_fd(int p_client_id, const unsigned char * message_buffer, int length_of_message) +{ + loggers::get_instance().log(">>> tcp_layer::send_message_on_fd: %d", p_client_id); + + if(get_user_data(p_client_id)) { + loggers::get_instance().log("tcp_layer::send_message_on_fd: SSL mode"); + return SSL_Socket::send_message_on_fd(p_client_id, message_buffer, length_of_message); + } + + loggers::get_instance().log("tcp_layer::send_message_on_fd: Non secured mode"); + return Abstract_Socket::send_message_on_fd(p_client_id, message_buffer, length_of_message); +} + +int tcp_layer::send_message_on_nonblocking_fd(int p_client_id, const unsigned char * message_buffer, int length_of_message) +{ + loggers::get_instance().log(">>> tcp_layer::send_message_on_nonblocking_fd: %d", p_client_id); + + if(get_user_data(p_client_id)) { + loggers::get_instance().log("tcp_layer::send_message_on_nonblocking_fd: SSL mode"); + return SSL_Socket::send_message_on_nonblocking_fd(p_client_id, message_buffer, length_of_message); + } + + loggers::get_instance().log("tcp_layer::send_message_on_nonblocking_fd: Non secured mode"); + return Abstract_Socket::send_message_on_nonblocking_fd(p_client_id, message_buffer, length_of_message); +} + +int tcp_layer::receive_message_on_fd(int p_client_id) +{ + loggers::get_instance().log(">>> tcp_layer::receive_message_on_fd: %d", p_client_id); + + if(get_user_data(p_client_id)) { + // INFO: it is assumed that only SSL_Socket assigns user data to each peer + loggers::get_instance().log("tcp_layer::receive_message_on_fd: SSL mode"); + return SSL_Socket::receive_message_on_fd(p_client_id); + } + + loggers::get_instance().log("tcp_layer::receive_message_on_fd: Non secured mode"); + if (_params[std::string("tcp_fragmented")].compare("1") == 0) { + sleep(5); // FIXME When HTTP paquet is fragmented into several TCP packets, a timer is required. This is a Q&D solution + } + return Abstract_Socket::receive_message_on_fd(p_client_id); +} + +void tcp_layer::peer_disconnected(int p_client_id) +{ + loggers::get_instance().log(">>> tcp_layer::peer_disconnected: %d", p_client_id); + + Abstract_Socket::peer_disconnected(p_client_id); + _client_id = -1; +} + +tcp_layer_factory tcp_layer_factory::_f; + diff --git a/ccsrc/Protocols/Tcp/tcp_layer.hh b/ccsrc/Protocols/Tcp/tcp_layer.hh index 917352203b8581d08edb6ca4bcb538fdd2a7b7b8..3a10bc46d4d22fc40f209955322bc0e05d0cb68c 100644 --- a/ccsrc/Protocols/Tcp/tcp_layer.hh +++ b/ccsrc/Protocols/Tcp/tcp_layer.hh @@ -1,98 +1,98 @@ -/*! - * \file tcp_layer.hh - * \brief Header file for ITS TCP socket based protocol port layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer.hh" - -using namespace std; // Required for isnan() -#include "Abstract_Socket.hh" - -class PORT; //! Forward declaration of TITAN class - -/*! - * \class tcp_layer - * \brief This class provides description of ITS TCP port protocol layer - */ -class tcp_layer : public layer, public SSL_Socket, public PORT { - params _params; //! Layer parameters - int _client_id; //! Connection identifier - std::string _time_key; //! \todo - bool _reconnect_on_send; //! Set to true if connection shall be done when sending data. Otherwise, connection is established by the \see constructor - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the tcp_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - tcp_layer(const std::string &p_type, const std::string &p_param); - /*! - * \brief Default destructor - * \remark If \see _reconnect_on_send is set to false, the disconnection is done by the destructor - */ - virtual ~tcp_layer(); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - * \virtual - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - /*! - * \virtual - * \fn void message_incoming(const unsigned char* message_buffer, int length, int client_id = -1); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_buffer The bytes formated data received - * \param[in] p_length The number of bytes received - * \param[in] p_client_id The connection identifier.Default: -1 - */ - virtual void message_incoming(const unsigned char *p_buffer, int p_length, int p_client_id = -1); - -protected: //! \protectedsection - void Add_Fd_Read_Handler(int fd) { Handler_Add_Fd_Read(fd); }; - void Add_Fd_Write_Handler(int fd) { Handler_Add_Fd_Write(fd); }; - void Remove_Fd_Read_Handler(int fd) { Handler_Remove_Fd_Read(fd); }; - void Remove_Fd_Write_Handler(int fd) { Handler_Remove_Fd_Write(fd); }; - void Remove_Fd_All_Handlers(int fd) { Handler_Remove_Fd(fd); }; - void Handler_Uninstall() { Uninstall_Handler(); } - void Timer_Set_Handler(double call_interval, boolean is_timeout = TRUE, boolean call_anyway = TRUE, boolean is_periodic = TRUE) { - Handler_Set_Timer(call_interval, is_timeout, call_anyway, is_periodic); - }; - - const char *remote_address_name() { return params::server.c_str(); }; - const char *remote_port_name() { return params::port.c_str(); }; - const char *socket_debugging_name() { return params::debug.c_str(); }; - const char *ssl_use_ssl_name() { return params::use_ssl.c_str(); }; - - void client_connection_opened(int p_client_id); - bool add_user_data(int p_client_id); - int send_message_on_fd(int p_client_id, const unsigned char *message_buffer, int length_of_message); - int send_message_on_nonblocking_fd(int client_id, const unsigned char *message_buffer, int length_of_message); - int receive_message_on_fd(int p_client_id); - void peer_disconnected(int p_client_id); - -private: //! \privatesection - void Handle_Fd_Event(int fd, boolean is_readable, boolean is_writable, boolean is_error); - void Handle_Timeout(double time_since_last_call); -}; // End of class tcp_layer +/*! + * \file tcp_layer.hh + * \brief Header file for ITS TCP socket based protocol port layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer.hh" + +using namespace std; // Required for isnan() +#include "Abstract_Socket.hh" + +class PORT; //! Forward declaration of TITAN class + +/*! + * \class tcp_layer + * \brief This class provides description of ITS TCP port protocol layer + */ +class tcp_layer : public layer, public SSL_Socket, public PORT { + params _params; //! Layer parameters + int _client_id; //! Connection identifier + std::string _time_key; //! \todo + bool _reconnect_on_send; //! Set to true if connection shall be done when sending data. Otherwise, connection is established by the \see constructor + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the tcp_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + tcp_layer(const std::string &p_type, const std::string &p_param); + /*! + * \brief Default destructor + * \remark If \see _reconnect_on_send is set to false, the disconnection is done by the destructor + */ + virtual ~tcp_layer(); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + * \virtual + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + /*! + * \virtual + * \fn void message_incoming(const unsigned char* message_buffer, int length, int client_id = -1); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_buffer The bytes formated data received + * \param[in] p_length The number of bytes received + * \param[in] p_client_id The connection identifier.Default: -1 + */ + virtual void message_incoming(const unsigned char *p_buffer, int p_length, int p_client_id = -1); + +protected: //! \protectedsection + void Add_Fd_Read_Handler(int fd) { Handler_Add_Fd_Read(fd); }; + void Add_Fd_Write_Handler(int fd) { Handler_Add_Fd_Write(fd); }; + void Remove_Fd_Read_Handler(int fd) { Handler_Remove_Fd_Read(fd); }; + void Remove_Fd_Write_Handler(int fd) { Handler_Remove_Fd_Write(fd); }; + void Remove_Fd_All_Handlers(int fd) { Handler_Remove_Fd(fd); }; + void Handler_Uninstall() { Uninstall_Handler(); } + void Timer_Set_Handler(double call_interval, boolean is_timeout = TRUE, boolean call_anyway = TRUE, boolean is_periodic = TRUE) { + Handler_Set_Timer(call_interval, is_timeout, call_anyway, is_periodic); + }; + + const char *remote_address_name() { return params::server.c_str(); }; + const char *remote_port_name() { return params::port.c_str(); }; + const char *socket_debugging_name() { return params::debug.c_str(); }; + const char *ssl_use_ssl_name() { return params::use_ssl.c_str(); }; + + void client_connection_opened(int p_client_id); + bool add_user_data(int p_client_id); + int send_message_on_fd(int p_client_id, const unsigned char *message_buffer, int length_of_message); + int send_message_on_nonblocking_fd(int client_id, const unsigned char *message_buffer, int length_of_message); + int receive_message_on_fd(int p_client_id); + void peer_disconnected(int p_client_id); + +private: //! \privatesection + void Handle_Fd_Event(int fd, boolean is_readable, boolean is_writable, boolean is_error); + void Handle_Timeout(double time_since_last_call); +}; // End of class tcp_layer diff --git a/ccsrc/Protocols/Tcp/tcp_layer_factory.hh b/ccsrc/Protocols/Tcp/tcp_layer_factory.hh index e173b477b1ff512fa90a15ae23856d874a70e895..4fe20098388966ef95bf6a77288a5b97974be92b 100644 --- a/ccsrc/Protocols/Tcp/tcp_layer_factory.hh +++ b/ccsrc/Protocols/Tcp/tcp_layer_factory.hh @@ -1,41 +1,41 @@ -/*! - * \file tcp_layer_factory.hh - * \brief Header file for ITS TCP socket based protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "tcp_layer.hh" - -/*! - * \class tcp_layer_factory - * \brief This class provides a factory class to create an tcp_layer class instance - */ -class tcp_layer_factory : public layer_factory { - static tcp_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the tcp_layer class - * \remark The TCP socket based layer identifier is TCP - */ - tcp_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("TCP", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new tcp_layer(p_type, p_param); }; -}; // End of class tcp_layer_factory +/*! + * \file tcp_layer_factory.hh + * \brief Header file for ITS TCP socket based protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "tcp_layer.hh" + +/*! + * \class tcp_layer_factory + * \brief This class provides a factory class to create an tcp_layer class instance + */ +class tcp_layer_factory : public layer_factory { + static tcp_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the tcp_layer class + * \remark The TCP socket based layer identifier is TCP + */ + tcp_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("TCP", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new tcp_layer(p_type, p_param); }; +}; // End of class tcp_layer_factory diff --git a/ccsrc/Protocols/UDP/module.mk b/ccsrc/Protocols/UDP/module.mk index b57564e5efa1cefe985a012f2f1e79c856132650..d19e9d9b5a24c14906c34531bbb2c094d8e54b7a 100644 --- a/ccsrc/Protocols/UDP/module.mk +++ b/ccsrc/Protocols/UDP/module.mk @@ -1,4 +1,4 @@ -#sources := udp_layer.cc udp_pcap_layer.cc -sources := udp_layer.cc -includes := . - +#sources := udp_layer.cc udp_pcap_layer.cc +sources := udp_layer.cc +includes := . + diff --git a/ccsrc/Protocols/UDP/udp_layer.cc b/ccsrc/Protocols/UDP/udp_layer.cc index ede5e26e98a57e521628db823d03b7a094ce80a1..422c96a3be25dae028d54859d24e564254864d4e 100644 --- a/ccsrc/Protocols/UDP/udp_layer.cc +++ b/ccsrc/Protocols/UDP/udp_layer.cc @@ -1,177 +1,177 @@ -#include -#include -#include - -#include - -#include "loggers.hh" - -#include "udp_layer_factory.hh" - -#include -#include - -udp_layer::udp_layer(const std::string &p_type, const std::string ¶m) - : layer(p_type), PORT(p_type.c_str()), _params(), _saddr{0}, _daddr{0}, _reuse_incoming_source_adddress(false), _fd(-1), - _time_key("udp_layer::Handle_Fd_Event_Readable") { - loggers::get_instance().log(">>> udp_layer::udp_layer: %s, %s", to_string().c_str(), param.c_str()); - - // Setup parameters - params::convert(_params, param); - params::const_iterator it = _params.find("src_ip"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("src_ip"), "127.0.0.1")); - } - it = _params.find("src_port"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("src_port"), "0")); // Dynamic binding requested - } - it = _params.find("dst_ip"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("dst_ip"), "127.0.0.1")); - } - it = _params.find("dst_port"); - if (it == _params.cend()) { - _params.insert(std::pair(std::string("dst_port"), "12345")); - } - it = _params.find("reuse_incoming_source_adddress"); - if (it != _params.cend()) { - _reuse_incoming_source_adddress = (boolean)(it->second.compare("1") == 0); - } - loggers::get_instance().log("udp_layer::udp_layer: _reuse_incoming_source_adddress: %d", _reuse_incoming_source_adddress); - - // Initialize the socket - _saddr.sin_family = AF_INET; - _saddr.sin_addr.s_addr = htonl(INADDR_ANY); - loggers::get_instance().log("udp_layer::udp_layer: Port to listen=%d", std::atoi(_params["src_port"].c_str())); - _saddr.sin_port = htons(std::atoi(_params["src_port"].c_str())); - // Create socket - _fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - if (_fd == -1) { - loggers::get_instance().error("udp_layer::udp_layer: Failed to create socket"); - } - loggers::get_instance().log("udp_layer::udp_layer: socket id: %d", _fd); - int reuse = 1; - if (::setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { - loggers::get_instance().warning("udp_layer::udp_layer: Failed to set SO_REUSEADDR"); - } - // Bind it - /*struct ifreq ifr; - memset(&ifr, 0, sizeof(ifr)); - snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth1"); - if (setsockopt(_fd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr.ifr_name, strlen(ifr.ifr_name)) < 0) { - close(); - loggers::get_instance().error("udp_layer::udp_layer: Failed to bind socket to %s", ifr.ifr_name); - } - loggers::get_instance().log("udp_layer::udp_layer: Bound to device %s", ifr.ifr_name);*/ - if (::bind(_fd, (struct sockaddr *)&_saddr, sizeof(_saddr)) < 0) { - close(); - loggers::get_instance().error("udp_layer::udp_layer: Failed to bind socket"); - } - loggers::get_instance().log("udp_layer::udp_layer: Bound on port %s", _params["src_port"].c_str()); - // Pass the device file handler to the polling procedure - Handler_Add_Fd_Read(_fd); - - _daddr.sin_family = AF_INET; - _daddr.sin_addr.s_addr = htonl(get_host_id(_params["dst_ip"])); - _daddr.sin_port = htons(std::atoi(_params["dst_port"].c_str())); -} - -udp_layer::~udp_layer() { - loggers::get_instance().log(">>> udp_layer::~udp_layer"); - - close(); -} - -void udp_layer::close() { - loggers::get_instance().log(">>> udp_layer::close: %d", _fd); - - if (_fd != -1) { - ::close(_fd); - _fd = -1; - } -} - -void udp_layer::send_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> udp_layer::send_data: ", data); - - int result = ::sendto(_fd, (const char *)static_cast(data), data.lengthof(), 0, (struct sockaddr *)&_daddr, sizeof(_daddr)); - loggers::get_instance().log("udp_layer::send_data: #bytes sent: %d to %s:%d", result, ::inet_ntoa(_daddr.sin_addr), ntohs(_daddr.sin_port)); -} - -void udp_layer::receive_data(OCTETSTRING &data, params ¶ms) { - loggers::get_instance().log_msg(">>> udp_layer::receive_data: ", data); - - receive_to_all_layers(data, params); -} - -void udp_layer::Handle_Fd_Event_Readable(int fd) { - loggers::get_instance().log(">>> udp_layer::Handle_Fd_Event_Readable: %d", fd); - - unsigned char buffer[3072] = {0}; - struct sockaddr_in from = {0}; - socklen_t len = sizeof(struct sockaddr_in); // Length of sender's address - params params; - std::vector acc; - int result = ::recvfrom(_fd, buffer, 3072, 0, (struct sockaddr *)&from, &len); - loggers::get_instance().log("udp_layer::Handle_Fd_Event_Readable: src_port = %s:%d, payload length = %d, errno = %d", ::inet_ntoa(from.sin_addr), - ntohs(from.sin_port), result, errno); - while ((result == 3072) && (errno == 0)) { - std::copy((unsigned char *)buffer, (unsigned char *)((unsigned char *)buffer + result), std::back_inserter(acc)); - result = ::recvfrom(_fd, buffer, 3072, 0, (struct sockaddr *)&from, &len); - loggers::get_instance().log("udp_layer::Handle_Fd_Event_Readable: src_port = %s:%d, payload length = %d, errno = %d", ::inet_ntoa(from.sin_addr), - ntohs(from.sin_port), result, errno); - } // End of 'while' statement - if (errno < 0) { - loggers::get_instance().warning("udp_layer::Handle_Fd_Event_Readable: Failed to read data, discard them: errno=%d", errno); - return; - } else { - std::copy((unsigned char *)buffer, (unsigned char *)((unsigned char *)buffer + result), std::back_inserter(acc)); - if (_reuse_incoming_source_adddress) { // Reuse the incoming address/port for sending - memcpy((void *)&_daddr, (const void *)&from, sizeof(struct sockaddr_in)); - loggers::get_instance().log("udp_layer::Handle_Fd_Event_Readable: New _daddr: %s:%d", ::inet_ntoa(_daddr.sin_addr), ntohs(_daddr.sin_port)); - } - } - params.insert(std::pair( - std::string("timestamp"), - std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()))); - - float duration; - loggers::get_instance().set_start_time(_time_key); - OCTETSTRING os(acc.size(), acc.data()); - receive_data(os, params); // TODO Check execution time for decoding operation - loggers::get_instance().set_stop_time(_time_key, duration); -} - -unsigned long udp_layer::get_host_id(const std::string &p_host_name) { - loggers::get_instance().log(">>> udp_layer::get_host_id"); - - if (p_host_name.empty()) { - loggers::get_instance().warning("udp_layer::get_host_id: Wrong parameter"); - return INADDR_ANY; - } - - unsigned long ip_addr = 0; - if (p_host_name.compare("255.255.255.255") == 0) { - loggers::get_instance().warning("udp_layer::get_host_id: Host ip is 255.255.255.255"); - ip_addr = 0xffffffff; - } else { - in_addr_t addr = ::inet_addr(p_host_name.c_str()); - if (addr != (in_addr_t)-1) { // host name in XX:XX:XX:XX form - ip_addr = addr; - } else { // host name in domain.com form - struct hostent *hptr; - if ((hptr = ::gethostbyname(p_host_name.c_str())) == 0) { - close(); - loggers::get_instance().error("udp_layer::get_host_id: Invalid host name: %s", p_host_name.c_str()); - } - ip_addr = *((unsigned long *)hptr->h_addr_list[0]); - } - } - - loggers::get_instance().log("udp_layer::get_host_id: Host name: %s, Host address: %u", p_host_name.c_str(), ip_addr); - - return htonl(ip_addr); -} - -udp_layer_factory udp_layer_factory::_f; +#include +#include +#include + +#include + +#include "loggers.hh" + +#include "udp_layer_factory.hh" + +#include +#include + +udp_layer::udp_layer(const std::string &p_type, const std::string ¶m) + : layer(p_type), PORT(p_type.c_str()), _params(), _saddr{0}, _daddr{0}, _reuse_incoming_source_adddress(false), _fd(-1), + _time_key("udp_layer::Handle_Fd_Event_Readable") { + loggers::get_instance().log(">>> udp_layer::udp_layer: %s, %s", to_string().c_str(), param.c_str()); + + // Setup parameters + params::convert(_params, param); + params::const_iterator it = _params.find("src_ip"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("src_ip"), "127.0.0.1")); + } + it = _params.find("src_port"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("src_port"), "0")); // Dynamic binding requested + } + it = _params.find("dst_ip"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("dst_ip"), "127.0.0.1")); + } + it = _params.find("dst_port"); + if (it == _params.cend()) { + _params.insert(std::pair(std::string("dst_port"), "12345")); + } + it = _params.find("reuse_incoming_source_adddress"); + if (it != _params.cend()) { + _reuse_incoming_source_adddress = (boolean)(it->second.compare("1") == 0); + } + loggers::get_instance().log("udp_layer::udp_layer: _reuse_incoming_source_adddress: %d", _reuse_incoming_source_adddress); + + // Initialize the socket + _saddr.sin_family = AF_INET; + _saddr.sin_addr.s_addr = htonl(INADDR_ANY); + loggers::get_instance().log("udp_layer::udp_layer: Port to listen=%d", std::atoi(_params["src_port"].c_str())); + _saddr.sin_port = htons(std::atoi(_params["src_port"].c_str())); + // Create socket + _fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (_fd == -1) { + loggers::get_instance().error("udp_layer::udp_layer: Failed to create socket"); + } + loggers::get_instance().log("udp_layer::udp_layer: socket id: %d", _fd); + int reuse = 1; + if (::setsockopt(_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) { + loggers::get_instance().warning("udp_layer::udp_layer: Failed to set SO_REUSEADDR"); + } + // Bind it + /*struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); + snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth1"); + if (setsockopt(_fd, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr.ifr_name, strlen(ifr.ifr_name)) < 0) { + close(); + loggers::get_instance().error("udp_layer::udp_layer: Failed to bind socket to %s", ifr.ifr_name); + } + loggers::get_instance().log("udp_layer::udp_layer: Bound to device %s", ifr.ifr_name);*/ + if (::bind(_fd, (struct sockaddr *)&_saddr, sizeof(_saddr)) < 0) { + close(); + loggers::get_instance().error("udp_layer::udp_layer: Failed to bind socket"); + } + loggers::get_instance().log("udp_layer::udp_layer: Bound on port %s", _params["src_port"].c_str()); + // Pass the device file handler to the polling procedure + Handler_Add_Fd_Read(_fd); + + _daddr.sin_family = AF_INET; + _daddr.sin_addr.s_addr = htonl(get_host_id(_params["dst_ip"])); + _daddr.sin_port = htons(std::atoi(_params["dst_port"].c_str())); +} + +udp_layer::~udp_layer() { + loggers::get_instance().log(">>> udp_layer::~udp_layer"); + + close(); +} + +void udp_layer::close() { + loggers::get_instance().log(">>> udp_layer::close: %d", _fd); + + if (_fd != -1) { + ::close(_fd); + _fd = -1; + } +} + +void udp_layer::send_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> udp_layer::send_data: ", data); + + int result = ::sendto(_fd, (const char *)static_cast(data), data.lengthof(), 0, (struct sockaddr *)&_daddr, sizeof(_daddr)); + loggers::get_instance().log("udp_layer::send_data: #bytes sent: %d to %s:%d", result, ::inet_ntoa(_daddr.sin_addr), ntohs(_daddr.sin_port)); +} + +void udp_layer::receive_data(OCTETSTRING &data, params ¶ms) { + loggers::get_instance().log_msg(">>> udp_layer::receive_data: ", data); + + receive_to_all_layers(data, params); +} + +void udp_layer::Handle_Fd_Event_Readable(int fd) { + loggers::get_instance().log(">>> udp_layer::Handle_Fd_Event_Readable: %d", fd); + + unsigned char buffer[3072] = {0}; + struct sockaddr_in from = {0}; + socklen_t len = sizeof(struct sockaddr_in); // Length of sender's address + params params; + std::vector acc; + int result = ::recvfrom(_fd, buffer, 3072, 0, (struct sockaddr *)&from, &len); + loggers::get_instance().log("udp_layer::Handle_Fd_Event_Readable: src_port = %s:%d, payload length = %d, errno = %d", ::inet_ntoa(from.sin_addr), + ntohs(from.sin_port), result, errno); + while ((result == 3072) && (errno == 0)) { + std::copy((unsigned char *)buffer, (unsigned char *)((unsigned char *)buffer + result), std::back_inserter(acc)); + result = ::recvfrom(_fd, buffer, 3072, 0, (struct sockaddr *)&from, &len); + loggers::get_instance().log("udp_layer::Handle_Fd_Event_Readable: src_port = %s:%d, payload length = %d, errno = %d", ::inet_ntoa(from.sin_addr), + ntohs(from.sin_port), result, errno); + } // End of 'while' statement + if (errno < 0) { + loggers::get_instance().warning("udp_layer::Handle_Fd_Event_Readable: Failed to read data, discard them: errno=%d", errno); + return; + } else { + std::copy((unsigned char *)buffer, (unsigned char *)((unsigned char *)buffer + result), std::back_inserter(acc)); + if (_reuse_incoming_source_adddress) { // Reuse the incoming address/port for sending + memcpy((void *)&_daddr, (const void *)&from, sizeof(struct sockaddr_in)); + loggers::get_instance().log("udp_layer::Handle_Fd_Event_Readable: New _daddr: %s:%d", ::inet_ntoa(_daddr.sin_addr), ntohs(_daddr.sin_port)); + } + } + params.insert(std::pair( + std::string("timestamp"), + std::to_string(std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count()))); + + float duration; + loggers::get_instance().set_start_time(_time_key); + OCTETSTRING os(acc.size(), acc.data()); + receive_data(os, params); // TODO Check execution time for decoding operation + loggers::get_instance().set_stop_time(_time_key, duration); +} + +unsigned long udp_layer::get_host_id(const std::string &p_host_name) { + loggers::get_instance().log(">>> udp_layer::get_host_id"); + + if (p_host_name.empty()) { + loggers::get_instance().warning("udp_layer::get_host_id: Wrong parameter"); + return INADDR_ANY; + } + + unsigned long ip_addr = 0; + if (p_host_name.compare("255.255.255.255") == 0) { + loggers::get_instance().warning("udp_layer::get_host_id: Host ip is 255.255.255.255"); + ip_addr = 0xffffffff; + } else { + in_addr_t addr = ::inet_addr(p_host_name.c_str()); + if (addr != (in_addr_t)-1) { // host name in XX:XX:XX:XX form + ip_addr = addr; + } else { // host name in domain.com form + struct hostent *hptr; + if ((hptr = ::gethostbyname(p_host_name.c_str())) == 0) { + close(); + loggers::get_instance().error("udp_layer::get_host_id: Invalid host name: %s", p_host_name.c_str()); + } + ip_addr = *((unsigned long *)hptr->h_addr_list[0]); + } + } + + loggers::get_instance().log("udp_layer::get_host_id: Host name: %s, Host address: %u", p_host_name.c_str(), ip_addr); + + return htonl(ip_addr); +} + +udp_layer_factory udp_layer_factory::_f; diff --git a/ccsrc/Protocols/UDP/udp_layer.hh b/ccsrc/Protocols/UDP/udp_layer.hh index c79e02f9f301cad3357736a30c21ac506aaa85c1..1f6fcc8157585ecaad03d9e14a5a188aa1bca28e 100644 --- a/ccsrc/Protocols/UDP/udp_layer.hh +++ b/ccsrc/Protocols/UDP/udp_layer.hh @@ -1,71 +1,71 @@ -/*! - * \file udp_layer.hh - * \brief Header file for ITS UDP/IP protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -#include "params.hh" -#include "t_layer.hh" - -class PORT; //! Forward declaration of TITAN class - -/*! - * \class udp_layer - * \brief This class provides description of ITS UDP/IP protocol layer - */ -class udp_layer : public layer, public PORT { - params _params; //! Layer parameters - struct sockaddr_in _saddr; //! Source socket address description - struct sockaddr_in _daddr; //! Destination socket address description - boolean _reuse_incoming_source_adddress; - //! This flag must be set to true if the UpperTester/UDP layer must act as an IUT, not as a Test System. Default value: Test System - int _fd; // Socket file descriptor - std::string _time_key; //! \todo - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the udp_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - udp_layer(const std::string &p_type, const std::string &p_param); - /*! - * \brief Default destructor - */ - virtual ~udp_layer(); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &data, params ¶ms); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &data, params &info); - - void Handle_Fd_Event_Readable(int fd); - -private: - unsigned long get_host_id(const std::string &p_host_name); - void close(); -}; // End of class udp_layer +/*! + * \file udp_layer.hh + * \brief Header file for ITS UDP/IP protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +#include "params.hh" +#include "t_layer.hh" + +class PORT; //! Forward declaration of TITAN class + +/*! + * \class udp_layer + * \brief This class provides description of ITS UDP/IP protocol layer + */ +class udp_layer : public layer, public PORT { + params _params; //! Layer parameters + struct sockaddr_in _saddr; //! Source socket address description + struct sockaddr_in _daddr; //! Destination socket address description + boolean _reuse_incoming_source_adddress; + //! This flag must be set to true if the UpperTester/UDP layer must act as an IUT, not as a Test System. Default value: Test System + int _fd; // Socket file descriptor + std::string _time_key; //! \todo + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the udp_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + udp_layer(const std::string &p_type, const std::string &p_param); + /*! + * \brief Default destructor + */ + virtual ~udp_layer(); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &data, params ¶ms); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &data, params &info); + + void Handle_Fd_Event_Readable(int fd); + +private: + unsigned long get_host_id(const std::string &p_host_name); + void close(); +}; // End of class udp_layer diff --git a/ccsrc/Protocols/UDP/udp_layer_factory.hh b/ccsrc/Protocols/UDP/udp_layer_factory.hh index 78218868353800cc6969d7e09b2e3c524f104bfd..d08c50332e6b8fbc9a80d2f0153efaa8223292f9 100644 --- a/ccsrc/Protocols/UDP/udp_layer_factory.hh +++ b/ccsrc/Protocols/UDP/udp_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file udp_layer_factory.hh - * \brief Header file for ITS UDP/IP protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "udp_layer.hh" - -/*! - * \class udp_layer_factory - * \brief This class provides a factory class to create an udp_layer class instance - */ -class udp_layer_factory : public layer_factory { - static udp_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the udp_layer_factory class - * \remark The UDP/IP layer identifier is UDP - */ - udp_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("UDP", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new udp_layer(p_type, p_param); }; -}; // End of class udp_layer_factory +/*! + * \file udp_layer_factory.hh + * \brief Header file for ITS UDP/IP protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "udp_layer.hh" + +/*! + * \class udp_layer_factory + * \brief This class provides a factory class to create an udp_layer class instance + */ +class udp_layer_factory : public layer_factory { + static udp_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the udp_layer_factory class + * \remark The UDP/IP layer identifier is UDP + */ + udp_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("UDP", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new udp_layer(p_type, p_param); }; +}; // End of class udp_layer_factory diff --git a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.cc b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.cc index dadce4d6f04289c70698d96a544b5ee1c4a2a2eb..ed170b65507f2a186d5de25b3bdd2ebf7bd58688 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.cc +++ b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.cc @@ -1,162 +1,162 @@ -#include -//#include - -#include "UpperTesterRtcmemCodec.hh" -#include "loggers.hh" - -#include "RtcmemCodec.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char UpperTesterRtcmemCodec::c_utRtcmemInitialize = 0x00; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemInitializeResult = 0x01; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemTrigger = 0xC0; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemTriggerResult = 0xC1; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemUpdate = 0xC2; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemUpdateResult = 0xC3; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemTermination = 0xC4; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemTerminationResult = 0xC5; -unsigned char UpperTesterRtcmemCodec::c_utRtcmemEventIndication = 0xC6; - -int UpperTesterRtcmemCodec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemCodec::encode: ", (const Record_Type &)msg); - loggers::get_instance().log(">>> UpperTesterRtcmemCodec::encode: %s", msg.get_descriptor()->name); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemInitialize") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemInitialize)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemTrigger") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTrigger)); - const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &trigger = dynamic_cast(msg); - unsigned char flag = 0x00; - if (trigger.timeStamp().is_present()) { - flag |= 0x80; - } - if (trigger.anchorPoint().is_present()) { - flag |= 0x40; - } - if (trigger.rtcmHeader().is_present()) { - flag |= 0x20; - } - encoding_buffer.put_c(flag); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemUpdate") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemUpdate)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemTermination") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTermination)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().log("<<< UpperTesterRtcmemCodec::encode: Return -1"); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::encode: data=", data); - return 0; -} - -int UpperTesterRtcmemCodec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> UpperTesterRtcmemCodec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, - dynamic_cast(&type)); - loggers::get_instance().log_msg(">>> UpperTesterRtcmemCodec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("UpperTesterRtcmemCodec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("UpperTesterRtcmemCodec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("UpperTesterRtcmemCodec::encode_: -1 result code returned"); - return -1; - } - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - loggers::get_instance().log("UpperTesterRtcmemCodec::encode_: field to process %s", s.c_str()); - if (s.compare("@LibItsRtcmem_TypesAndValues.UtRtcmemTrigger.msgs") == 0) { - const PreGenRecordOf::PREGEN__RECORD__OF__OCTETSTRING &rov = dynamic_cast(type); - encoding_buffer.put_c(static_cast(rov.lengthof())); - for (int i = 0; i < rov.lengthof(); i++) { - const OCTETSTRING &os = rov[i]; - encoding_buffer.put_c(static_cast(os.lengthof())); - encoding_buffer.put_os(os); - } // End of 'for' statement - } else { - loggers::get_instance().log("UpperTesterRtcmemCodec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_OER); // HashId8 - } - } - - loggers::get_instance().log_to_hexa("<<>> UpperTesterRtcmemCodec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr UpperTesterRtcmemCodec::decode(const OCTETSTRING &data, params *params) { - std::unique_ptr result; - - const unsigned char *ptr = static_cast(data); - if (*ptr != UpperTesterRtcmemCodec::c_utRtcmemEventIndication) { - LibItsRtcmem__TypesAndValues::UtRtcmemResults res; - decode(data, res, params); - result.reset((Base_Type *)res.clone()); - } else { - LibItsRtcmem__TypesAndValues::UtRtcmemEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } - - return result; -} - -int UpperTesterRtcmemCodec::decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemResults &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> UpperTesterRtcmemCodec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemInitializeResult) { - msg.utRtcmemInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemTriggerResult) { - msg.utRtcmemTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemUpdateResult) { - msg.utRtcmemUpdateResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemTerminationResult) { - msg.utRtcmemTerminationResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else { - TTCN_warning("UpperTesterRtcmemCodec::decode: Unsupported result"); - } - - loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::decode", msg); - return 0; -} - -int UpperTesterRtcmemCodec::decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> UpperTesterRtcmemCodec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data) + 1; - OCTETSTRING os(2, ptr); - ptr += 2; - unsigned int length = oct2int(os); - loggers::get_instance().log("UpperTesterRtcmemCodec::decode: RTCMEM message length=%d", length); - os = OCTETSTRING(length, ptr); - loggers::get_instance().log_to_hexa("UpperTesterRtcmemCodec::decode: RTCMEM message=", os); - RtcmemCodec codec; - codec.decode(os, msg.rtcmemMsg(), params); - - loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::decode", msg); - return 0; -} +#include +//#include + +#include "UpperTesterRtcmemCodec.hh" +#include "loggers.hh" + +#include "RtcmemCodec.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char UpperTesterRtcmemCodec::c_utRtcmemInitialize = 0x00; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemInitializeResult = 0x01; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemTrigger = 0xC0; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemTriggerResult = 0xC1; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemUpdate = 0xC2; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemUpdateResult = 0xC3; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemTermination = 0xC4; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemTerminationResult = 0xC5; +unsigned char UpperTesterRtcmemCodec::c_utRtcmemEventIndication = 0xC6; + +int UpperTesterRtcmemCodec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemCodec::encode: ", (const Record_Type &)msg); + loggers::get_instance().log(">>> UpperTesterRtcmemCodec::encode: %s", msg.get_descriptor()->name); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemInitialize") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemInitialize)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemTrigger") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTrigger)); + const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &trigger = dynamic_cast(msg); + unsigned char flag = 0x00; + if (trigger.timeStamp().is_present()) { + flag |= 0x80; + } + if (trigger.anchorPoint().is_present()) { + flag |= 0x40; + } + if (trigger.rtcmHeader().is_present()) { + flag |= 0x20; + } + encoding_buffer.put_c(flag); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemUpdate") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemUpdate)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsRtcmem_TypesAndValues.UtRtcmemTermination") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterRtcmemCodec::c_utRtcmemTermination)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().log("<<< UpperTesterRtcmemCodec::encode: Return -1"); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::encode: data=", data); + return 0; +} + +int UpperTesterRtcmemCodec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> UpperTesterRtcmemCodec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, + dynamic_cast(&type)); + loggers::get_instance().log_msg(">>> UpperTesterRtcmemCodec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("UpperTesterRtcmemCodec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("UpperTesterRtcmemCodec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("UpperTesterRtcmemCodec::encode_: -1 result code returned"); + return -1; + } + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + loggers::get_instance().log("UpperTesterRtcmemCodec::encode_: field to process %s", s.c_str()); + if (s.compare("@LibItsRtcmem_TypesAndValues.UtRtcmemTrigger.msgs") == 0) { + const PreGenRecordOf::PREGEN__RECORD__OF__OCTETSTRING &rov = dynamic_cast(type); + encoding_buffer.put_c(static_cast(rov.lengthof())); + for (int i = 0; i < rov.lengthof(); i++) { + const OCTETSTRING &os = rov[i]; + encoding_buffer.put_c(static_cast(os.lengthof())); + encoding_buffer.put_os(os); + } // End of 'for' statement + } else { + loggers::get_instance().log("UpperTesterRtcmemCodec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_OER); // HashId8 + } + } + + loggers::get_instance().log_to_hexa("<<>> UpperTesterRtcmemCodec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr UpperTesterRtcmemCodec::decode(const OCTETSTRING &data, params *params) { + std::unique_ptr result; + + const unsigned char *ptr = static_cast(data); + if (*ptr != UpperTesterRtcmemCodec::c_utRtcmemEventIndication) { + LibItsRtcmem__TypesAndValues::UtRtcmemResults res; + decode(data, res, params); + result.reset((Base_Type *)res.clone()); + } else { + LibItsRtcmem__TypesAndValues::UtRtcmemEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } + + return result; +} + +int UpperTesterRtcmemCodec::decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemResults &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> UpperTesterRtcmemCodec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemInitializeResult) { + msg.utRtcmemInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemTriggerResult) { + msg.utRtcmemTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemUpdateResult) { + msg.utRtcmemUpdateResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == UpperTesterRtcmemCodec::c_utRtcmemTerminationResult) { + msg.utRtcmemTerminationResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else { + TTCN_warning("UpperTesterRtcmemCodec::decode: Unsupported result"); + } + + loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::decode", msg); + return 0; +} + +int UpperTesterRtcmemCodec::decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> UpperTesterRtcmemCodec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data) + 1; + OCTETSTRING os(2, ptr); + ptr += 2; + unsigned int length = oct2int(os); + loggers::get_instance().log("UpperTesterRtcmemCodec::decode: RTCMEM message length=%d", length); + os = OCTETSTRING(length, ptr); + loggers::get_instance().log_to_hexa("UpperTesterRtcmemCodec::decode: RTCMEM message=", os); + RtcmemCodec codec; + codec.decode(os, msg.rtcmemMsg(), params); + + loggers::get_instance().log_msg("<<< UpperTesterRtcmemCodec::decode", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.hh b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.hh index f890731c2096a03917434877f6918142e3cddd92..7dda869d497794b8c02f840773ce96727818f645 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.hh +++ b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemCodec.hh @@ -1,46 +1,46 @@ -#ifndef UpperTesterRtcmemCODEC_H -#define UpperTesterRtcmemCODEC_H - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsRtcmem__TypesAndValues { - class UtRtcmemResults; - class UtRtcmemEventInd; - class UtSsemEventInd; -} // namespace LibItsRtcmem__TypesAndValues - -class UpperTesterRtcmemCodec : public codec { -public: - static unsigned char c_utRtcmemInitialize; - static unsigned char c_utRtcmemInitializeResult; - static unsigned char c_utRtcmemTrigger; - static unsigned char c_utRtcmemTriggerResult; - static unsigned char c_utRtcmemUpdate; - static unsigned char c_utRtcmemUpdateResult; - static unsigned char c_utRtcmemTermination; - static unsigned char c_utRtcmemTerminationResult; - static unsigned char c_utRtcmemEventIndication; - - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - UpperTesterRtcmemCodec() : codec(){}; - virtual ~UpperTesterRtcmemCodec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &msg, params *params = NULL); -}; -#endif +#ifndef UpperTesterRtcmemCODEC_H +#define UpperTesterRtcmemCODEC_H + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsRtcmem__TypesAndValues { + class UtRtcmemResults; + class UtRtcmemEventInd; + class UtSsemEventInd; +} // namespace LibItsRtcmem__TypesAndValues + +class UpperTesterRtcmemCodec : public codec { +public: + static unsigned char c_utRtcmemInitialize; + static unsigned char c_utRtcmemInitializeResult; + static unsigned char c_utRtcmemTrigger; + static unsigned char c_utRtcmemTriggerResult; + static unsigned char c_utRtcmemUpdate; + static unsigned char c_utRtcmemUpdateResult; + static unsigned char c_utRtcmemTermination; + static unsigned char c_utRtcmemTerminationResult; + static unsigned char c_utRtcmemEventIndication; + + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + UpperTesterRtcmemCodec() : codec(){}; + virtual ~UpperTesterRtcmemCodec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsRtcmem__TypesAndValues::UtRtcmemEventInd &msg, params *params = NULL); +}; +#endif diff --git a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemFactory.hh b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemFactory.hh index 06bb6a849cb56094c8ec67ea598a1495e761fdc7..e0cd184b4eec4dd3109a8e91bc2d3ac4aee1e30b 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemFactory.hh +++ b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemFactory.hh @@ -1,26 +1,26 @@ -/*! - * \file UpperTesterRtcmemFactory.hh - * \brief Header file for ITS SREM/SSEM Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "UpperTesterRtcmemLayer.hh" - -class UpperTesterRtcmemFactory : public layer_factory { - static UpperTesterRtcmemFactory _f; - -public: - UpperTesterRtcmemFactory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_RTCMEM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new UpperTesterRtcmemLayer(p_type, p_param); }; -}; // End of class UpperTesterRtcmemFactory +/*! + * \file UpperTesterRtcmemFactory.hh + * \brief Header file for ITS SREM/SSEM Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "UpperTesterRtcmemLayer.hh" + +class UpperTesterRtcmemFactory : public layer_factory { + static UpperTesterRtcmemFactory _f; + +public: + UpperTesterRtcmemFactory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_RTCMEM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new UpperTesterRtcmemLayer(p_type, p_param); }; +}; // End of class UpperTesterRtcmemFactory diff --git a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.cc b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.cc index 4f5dadd8cbfec0640281c41c3cd2d251cf9dcc6a..0240f1b190205317978f46122649ba1597c3c6cb 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.cc +++ b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.cc @@ -1,71 +1,71 @@ -#include "UpperTesterRtcmemFactory.hh" - -#include "LibItsRtcmem_TestSystem.hh" -#include "LibItsRtcmem_TypesAndValues.hh" - -#include "loggers.hh" - -UpperTesterRtcmemLayer::UpperTesterRtcmemLayer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> UpperTesterRtcmemLayer::UpperTesterRtcmemLayer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); -} - -void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterRtcmemLayer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void UpperTesterRtcmemLayer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -UpperTesterRtcmemFactory UpperTesterRtcmemFactory::_f; +#include "UpperTesterRtcmemFactory.hh" + +#include "LibItsRtcmem_TestSystem.hh" +#include "LibItsRtcmem_TypesAndValues.hh" + +#include "loggers.hh" + +UpperTesterRtcmemLayer::UpperTesterRtcmemLayer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> UpperTesterRtcmemLayer::UpperTesterRtcmemLayer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); +} + +void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterRtcmemLayer::sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterRtcmemLayer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void UpperTesterRtcmemLayer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterRtcmemLayer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +UpperTesterRtcmemFactory UpperTesterRtcmemFactory::_f; diff --git a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.hh b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.hh index 2a39aea1b649da363a2d23350e17afd17ddac1f2..af7a89ceef58ec6b046bf5c01d3b1ec4d03a8d50 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.hh +++ b/ccsrc/Protocols/UpperTester/UpperTesterRtcmemLayer.hh @@ -1,36 +1,36 @@ -#ifndef UpperTesterRtcmem_LAYER_H -#define UpperTesterRtcmem_LAYER_H - -#include "UpperTesterRtcmemCodec.hh" -#include "t_layer.hh" - -namespace LibItsRtcmem__TestSystem { - class UpperTesterPort; -} - -namespace LibItsRtcmem__TypesAndValues { - class UtRtcmemInitialize; - class UtRtcmemTrigger; - class UtRtcmemUpdate; - class UtRtcmemTermination; -} // namespace LibItsRtcmem__TypesAndValues - -class UpperTesterRtcmemLayer : public t_layer { - params _params; - UpperTesterRtcmemCodec _codec; - -public: - UpperTesterRtcmemLayer() : t_layer(), _params(), _codec(){}; - UpperTesterRtcmemLayer(const std::string &p_type, const std::string ¶m); - virtual ~UpperTesterRtcmemLayer(){}; - - void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par, params &p_params); - void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par, params &p_params); - void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par, params &p_params); - void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; - -#endif +#ifndef UpperTesterRtcmem_LAYER_H +#define UpperTesterRtcmem_LAYER_H + +#include "UpperTesterRtcmemCodec.hh" +#include "t_layer.hh" + +namespace LibItsRtcmem__TestSystem { + class UpperTesterPort; +} + +namespace LibItsRtcmem__TypesAndValues { + class UtRtcmemInitialize; + class UtRtcmemTrigger; + class UtRtcmemUpdate; + class UtRtcmemTermination; +} // namespace LibItsRtcmem__TypesAndValues + +class UpperTesterRtcmemLayer : public t_layer { + params _params; + UpperTesterRtcmemCodec _codec; + +public: + UpperTesterRtcmemLayer() : t_layer(), _params(), _codec(){}; + UpperTesterRtcmemLayer(const std::string &p_type, const std::string ¶m); + virtual ~UpperTesterRtcmemLayer(){}; + + void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemInitialize &send_par, params &p_params); + void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTrigger &send_par, params &p_params); + void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemUpdate &send_par, params &p_params); + void sendMsg(const LibItsRtcmem__TypesAndValues::UtRtcmemTermination &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; + +#endif diff --git a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.cc b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.cc index 8c0652f453597874dc1361c07da4c211820157ea..7fdfc5080c98e679f8f5ea602cf0764587396364 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.cc +++ b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.cc @@ -1,175 +1,175 @@ -#include -//#include - -#include "UpperTesterSremSsemCodec.hh" -#include "loggers.hh" - -#include "LibItsSremSsem_TestSystem.hh" -#include "LibItsSremSsem_TypesAndValues.hh" - -#include "SremCodec.hh" -#include "SsemCodec.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char UpperTesterSremSsemCodec::c_utSremInitialize = 0x00; -unsigned char UpperTesterSremSsemCodec::c_utSremInitializeResult = 0x01; -unsigned char UpperTesterSremSsemCodec::c_utSremTrigger = 0xA0; -unsigned char UpperTesterSremSsemCodec::c_utSremTriggerResult = 0xA1; -unsigned char UpperTesterSremSsemCodec::c_utSremUpdate = 0xA2; -unsigned char UpperTesterSremSsemCodec::c_utSremUpdateResult = 0xA3; -unsigned char UpperTesterSremSsemCodec::c_utSremCancelation = 0xA4; -unsigned char UpperTesterSremSsemCodec::c_utSremCancelationResult = 0xA5; -unsigned char UpperTesterSremSsemCodec::c_utSremEventIndication = 0xA6; -unsigned char UpperTesterSremSsemCodec::c_utSsemEventIndication = 0xA7; - -int UpperTesterSremSsemCodec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemCodec::encode: ", (const Record_Type &)msg); - loggers::get_instance().log(">>> UpperTesterSremSsemCodec::encode: %s", msg.get_descriptor()->name); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremInitialize") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremInitialize)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremTrigger") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremTrigger)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremUpdate") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremUpdate)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremCancelation") == 0) { - encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremCancelation)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().log("<<< UpperTesterSremSsemCodec::encode: Return -1"); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::encode: data=", data); - return 0; -} - -int UpperTesterSremSsemCodec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> UpperTesterSremSsemCodec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, - dynamic_cast(&type)); - loggers::get_instance().log_msg(">>> UpperTesterSremSsemCodec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("UpperTesterSremSsemCodec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("UpperTesterSremSsemCodec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", - r.fld_name(i), r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), - r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("UpperTesterSremSsemCodec::encode_: -1 result code returned"); - return -1; - } - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - loggers::get_instance().log("UpperTesterSremSsemCodec::encode_: field to process %s", s.c_str()); - loggers::get_instance().log("UpperTesterSremSsemCodec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_OER); - } - - loggers::get_instance().log_to_hexa("<<>> UpperTesterSremSsemCodec::decode (1): data=", data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - - loggers::get_instance().log_to_hexa("UpperTesterSremSsemCodec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, params *params) { - loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (2): decoding_buffer=", data); - - std::unique_ptr result; - - const unsigned char *ptr = static_cast(data); - if (*ptr == UpperTesterSremSsemCodec::c_utSsemEventIndication) { - LibItsSremSsem__TypesAndValues::UtSsemEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } else if (*ptr == UpperTesterSremSsemCodec::c_utSremEventIndication) { - LibItsSremSsem__TypesAndValues::UtSremEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } else { - LibItsSremSsem__TypesAndValues::UtSremResults res; - decode(data, res, params); - result.reset((Base_Type *)res.clone()); - } - - return result; -} - -int UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremResults &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (3): decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == UpperTesterSremSsemCodec::c_utSremInitializeResult) { - msg.utSremInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == UpperTesterSremSsemCodec::c_utSremTriggerResult) { - msg.utSremTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == UpperTesterSremSsemCodec::c_utSremUpdateResult) { - msg.utSremUpdateResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == UpperTesterSremSsemCodec::c_utSremCancelationResult) { - msg.utSremCancelationResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" - // Peer does not support the command - msg.utSremInitializeResult() = 0x00; - } else { - loggers::get_instance().warning("UpperTesterSremSsemCodec::decode (3): Unsupported result"); - return -1; - } - - loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode (3): ", msg); - return 0; -} - -int UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremEventInd &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (4): decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data) + 1; - OCTETSTRING os(2, ptr); - ptr += 2; - unsigned int length = oct2int(os); - loggers::get_instance().log("UpperTesterSremSsemCodec::decode: SREM message length=%d", length); - os = OCTETSTRING(length, ptr); - loggers::get_instance().log_to_hexa("UpperTesterSremSsemCodec::decode: SREM message=", os); - SremCodec codec; - codec.decode(os, msg.sreMsg(), params); - - loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode (4): ", msg); - return 0; -} - -int UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSsemEventInd &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (5): decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data) + 1; - OCTETSTRING os(2, ptr); - ptr += 2; - unsigned int length = oct2int(os); - loggers::get_instance().log("UpperTesterSremSsemCodec::decode: SSEM message length=%d", length); - os = OCTETSTRING(length, ptr); - loggers::get_instance().log_to_hexa("UpperTesterSremSsemCodec::decode: SSEM message=", os); - SsemCodec codec; - codec.decode(os, msg.sseMsg(), params); - - loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode (5): ", msg); - return 0; -} +#include +//#include + +#include "UpperTesterSremSsemCodec.hh" +#include "loggers.hh" + +#include "LibItsSremSsem_TestSystem.hh" +#include "LibItsSremSsem_TypesAndValues.hh" + +#include "SremCodec.hh" +#include "SsemCodec.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char UpperTesterSremSsemCodec::c_utSremInitialize = 0x00; +unsigned char UpperTesterSremSsemCodec::c_utSremInitializeResult = 0x01; +unsigned char UpperTesterSremSsemCodec::c_utSremTrigger = 0xA0; +unsigned char UpperTesterSremSsemCodec::c_utSremTriggerResult = 0xA1; +unsigned char UpperTesterSremSsemCodec::c_utSremUpdate = 0xA2; +unsigned char UpperTesterSremSsemCodec::c_utSremUpdateResult = 0xA3; +unsigned char UpperTesterSremSsemCodec::c_utSremCancelation = 0xA4; +unsigned char UpperTesterSremSsemCodec::c_utSremCancelationResult = 0xA5; +unsigned char UpperTesterSremSsemCodec::c_utSremEventIndication = 0xA6; +unsigned char UpperTesterSremSsemCodec::c_utSsemEventIndication = 0xA7; + +int UpperTesterSremSsemCodec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemCodec::encode: ", (const Record_Type &)msg); + loggers::get_instance().log(">>> UpperTesterSremSsemCodec::encode: %s", msg.get_descriptor()->name); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremInitialize") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremInitialize)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremTrigger") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremTrigger)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremUpdate") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremUpdate)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsSremSsem_TypesAndValues.UtSremCancelation") == 0) { + encoding_buffer.put_c(static_cast(UpperTesterSremSsemCodec::c_utSremCancelation)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().log("<<< UpperTesterSremSsemCodec::encode: Return -1"); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::encode: data=", data); + return 0; +} + +int UpperTesterSremSsemCodec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> UpperTesterSremSsemCodec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, + dynamic_cast(&type)); + loggers::get_instance().log_msg(">>> UpperTesterSremSsemCodec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("UpperTesterSremSsemCodec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("UpperTesterSremSsemCodec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", + r.fld_name(i), r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), + r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("UpperTesterSremSsemCodec::encode_: -1 result code returned"); + return -1; + } + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + loggers::get_instance().log("UpperTesterSremSsemCodec::encode_: field to process %s", s.c_str()); + loggers::get_instance().log("UpperTesterSremSsemCodec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_OER); + } + + loggers::get_instance().log_to_hexa("<<>> UpperTesterSremSsemCodec::decode (1): data=", data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + + loggers::get_instance().log_to_hexa("UpperTesterSremSsemCodec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, params *params) { + loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (2): decoding_buffer=", data); + + std::unique_ptr result; + + const unsigned char *ptr = static_cast(data); + if (*ptr == UpperTesterSremSsemCodec::c_utSsemEventIndication) { + LibItsSremSsem__TypesAndValues::UtSsemEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } else if (*ptr == UpperTesterSremSsemCodec::c_utSremEventIndication) { + LibItsSremSsem__TypesAndValues::UtSremEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } else { + LibItsSremSsem__TypesAndValues::UtSremResults res; + decode(data, res, params); + result.reset((Base_Type *)res.clone()); + } + + return result; +} + +int UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremResults &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (3): decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == UpperTesterSremSsemCodec::c_utSremInitializeResult) { + msg.utSremInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == UpperTesterSremSsemCodec::c_utSremTriggerResult) { + msg.utSremTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == UpperTesterSremSsemCodec::c_utSremUpdateResult) { + msg.utSremUpdateResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == UpperTesterSremSsemCodec::c_utSremCancelationResult) { + msg.utSremCancelationResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" + // Peer does not support the command + msg.utSremInitializeResult() = 0x00; + } else { + loggers::get_instance().warning("UpperTesterSremSsemCodec::decode (3): Unsupported result"); + return -1; + } + + loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode (3): ", msg); + return 0; +} + +int UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremEventInd &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (4): decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data) + 1; + OCTETSTRING os(2, ptr); + ptr += 2; + unsigned int length = oct2int(os); + loggers::get_instance().log("UpperTesterSremSsemCodec::decode: SREM message length=%d", length); + os = OCTETSTRING(length, ptr); + loggers::get_instance().log_to_hexa("UpperTesterSremSsemCodec::decode: SREM message=", os); + SremCodec codec; + codec.decode(os, msg.sreMsg(), params); + + loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode (4): ", msg); + return 0; +} + +int UpperTesterSremSsemCodec::decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSsemEventInd &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> UpperTesterSremSsemCodec::decode (5): decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data) + 1; + OCTETSTRING os(2, ptr); + ptr += 2; + unsigned int length = oct2int(os); + loggers::get_instance().log("UpperTesterSremSsemCodec::decode: SSEM message length=%d", length); + os = OCTETSTRING(length, ptr); + loggers::get_instance().log_to_hexa("UpperTesterSremSsemCodec::decode: SSEM message=", os); + SsemCodec codec; + codec.decode(os, msg.sseMsg(), params); + + loggers::get_instance().log_msg("<<< UpperTesterSremSsemCodec::decode (5): ", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.hh b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.hh index cd430a67a35c4d5d82181eaea0bdb21e8fcae473..74aa0641fb162639a36298caf94b92c16de3d28e 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.hh +++ b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemCodec.hh @@ -1,48 +1,48 @@ -#ifndef UpperTesterSremSsemCODEC_H -#define UpperTesterSremSsemCODEC_H - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsSremSsem__TypesAndValues { - class UtSremResults; - class UtSremEventInd; - class UtSsemEventInd; -} // namespace LibItsSremSsem__TypesAndValues - -class UpperTesterSremSsemCodec : public codec { -public: - static unsigned char c_utSremInitialize; - static unsigned char c_utSremInitializeResult; - static unsigned char c_utSremTrigger; - static unsigned char c_utSremTriggerResult; - static unsigned char c_utSremUpdate; - static unsigned char c_utSremUpdateResult; - static unsigned char c_utSremCancelation; - static unsigned char c_utSremCancelationResult; - static unsigned char c_utSremEventIndication; - static unsigned char c_utSsemEventIndication; - - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - UpperTesterSremSsemCodec() : codec(){}; - virtual ~UpperTesterSremSsemCodec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremEventInd &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSsemEventInd &msg, params *params = NULL); -}; -#endif +#ifndef UpperTesterSremSsemCODEC_H +#define UpperTesterSremSsemCODEC_H + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsSremSsem__TypesAndValues { + class UtSremResults; + class UtSremEventInd; + class UtSsemEventInd; +} // namespace LibItsSremSsem__TypesAndValues + +class UpperTesterSremSsemCodec : public codec { +public: + static unsigned char c_utSremInitialize; + static unsigned char c_utSremInitializeResult; + static unsigned char c_utSremTrigger; + static unsigned char c_utSremTriggerResult; + static unsigned char c_utSremUpdate; + static unsigned char c_utSremUpdateResult; + static unsigned char c_utSremCancelation; + static unsigned char c_utSremCancelationResult; + static unsigned char c_utSremEventIndication; + static unsigned char c_utSsemEventIndication; + + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + UpperTesterSremSsemCodec() : codec(){}; + virtual ~UpperTesterSremSsemCodec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSremEventInd &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsSremSsem__TypesAndValues::UtSsemEventInd &msg, params *params = NULL); +}; +#endif diff --git a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemFactory.hh b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemFactory.hh index b18a8089d27cbfa6b956c8a2a90f689b7160cae2..bae4ccfd63cc100a6d159737d12a722c7c808b49 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemFactory.hh +++ b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemFactory.hh @@ -1,26 +1,26 @@ -/*! - * \file UpperTesterSremSsemFactory.hh - * \brief Header file for ITS SREM/SSEM Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "UpperTesterSremSsemLayer.hh" - -class UpperTesterSremSsemFactory : public layer_factory { - static UpperTesterSremSsemFactory _f; - -public: - UpperTesterSremSsemFactory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_SREMSSEM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new UpperTesterSremSsemLayer(p_type, p_param); }; -}; // End of class UpperTesterSremSsemFactory +/*! + * \file UpperTesterSremSsemFactory.hh + * \brief Header file for ITS SREM/SSEM Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "UpperTesterSremSsemLayer.hh" + +class UpperTesterSremSsemFactory : public layer_factory { + static UpperTesterSremSsemFactory _f; + +public: + UpperTesterSremSsemFactory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_SREMSSEM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new UpperTesterSremSsemLayer(p_type, p_param); }; +}; // End of class UpperTesterSremSsemFactory diff --git a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.cc b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.cc index 655dbc79414a5d0b73c2e21f1d7f7fbfd42ac2ff..3c096f333176bebe380b26308debc6e4e22622b1 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.cc +++ b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.cc @@ -1,71 +1,71 @@ -#include "UpperTesterSremSsemFactory.hh" - -#include "LibItsSremSsem_TestSystem.hh" -#include "LibItsSremSsem_TypesAndValues.hh" - -#include "loggers.hh" - -UpperTesterSremSsemLayer::UpperTesterSremSsemLayer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> UpperTesterSremSsemLayer::UpperTesterSremSsemLayer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); -} - -void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void UpperTesterSremSsemLayer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void UpperTesterSremSsemLayer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -UpperTesterSremSsemFactory UpperTesterSremSsemFactory::_f; +#include "UpperTesterSremSsemFactory.hh" + +#include "LibItsSremSsem_TestSystem.hh" +#include "LibItsSremSsem_TypesAndValues.hh" + +#include "loggers.hh" + +UpperTesterSremSsemLayer::UpperTesterSremSsemLayer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> UpperTesterSremSsemLayer::UpperTesterSremSsemLayer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); +} + +void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterSremSsemLayer::sendMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void UpperTesterSremSsemLayer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void UpperTesterSremSsemLayer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> UpperTesterSremSsemLayer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +UpperTesterSremSsemFactory UpperTesterSremSsemFactory::_f; diff --git a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.hh b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.hh index d9d43e1e82136df9182f3f7d4e832bad97dbb986..59e010c2eade4397fda8dd378130fe4930856877 100644 --- a/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.hh +++ b/ccsrc/Protocols/UpperTester/UpperTesterSremSsemLayer.hh @@ -1,36 +1,36 @@ -#ifndef UpperTesterSremSsem_LAYER_H -#define UpperTesterSremSsem_LAYER_H - -#include "UpperTesterSremSsemCodec.hh" -#include "t_layer.hh" - -namespace LibItsSremSsem__TestSystem { - class UpperTesterPort; -} - -namespace LibItsSremSsem__TypesAndValues { - class UtSremInitialize; - class UtSremTrigger; - class UtSremUpdate; - class UtSremCancelation; -} // namespace LibItsSremSsem__TypesAndValues - -class UpperTesterSremSsemLayer : public t_layer { - params _params; - UpperTesterSremSsemCodec _codec; - -public: - UpperTesterSremSsemLayer() : t_layer(), _params(), _codec(){}; - UpperTesterSremSsemLayer(const std::string &p_type, const std::string ¶m); - virtual ~UpperTesterSremSsemLayer(){}; - - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par, params &p_params); - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par, params &p_params); - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par, params &p_params); - void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; - -#endif +#ifndef UpperTesterSremSsem_LAYER_H +#define UpperTesterSremSsem_LAYER_H + +#include "UpperTesterSremSsemCodec.hh" +#include "t_layer.hh" + +namespace LibItsSremSsem__TestSystem { + class UpperTesterPort; +} + +namespace LibItsSremSsem__TypesAndValues { + class UtSremInitialize; + class UtSremTrigger; + class UtSremUpdate; + class UtSremCancelation; +} // namespace LibItsSremSsem__TypesAndValues + +class UpperTesterSremSsemLayer : public t_layer { + params _params; + UpperTesterSremSsemCodec _codec; + +public: + UpperTesterSremSsemLayer() : t_layer(), _params(), _codec(){}; + UpperTesterSremSsemLayer(const std::string &p_type, const std::string ¶m); + virtual ~UpperTesterSremSsemLayer(){}; + + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremInitialize &send_par, params &p_params); + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremTrigger &send_par, params &p_params); + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremUpdate &send_par, params &p_params); + void sendMsg(const LibItsSremSsem__TypesAndValues::UtSremCancelation &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; + +#endif diff --git a/ccsrc/Protocols/UpperTester/module.mk b/ccsrc/Protocols/UpperTester/module.mk index c600f5f44b6dcbc6251cfd7fdca65685d9bac978..95d8e8363868cecc50c6ddc5aa7a5fcb5d8efc04 100644 --- a/ccsrc/Protocols/UpperTester/module.mk +++ b/ccsrc/Protocols/UpperTester/module.mk @@ -7,24 +7,21 @@ endif #ifeq (AtsGeoNetworking, $(ATS)) #sources += uppertester_geonetworking_codec.cc uppertester_geonetworking_layer.cc #endif -ifeq (AtsIVIM, $(ATS)) -sources += uppertester_ivim_codec.cc uppertester_ivim_layer.cc + +ifeq (AtsDENM, $(ATS)) +sources += uppertester_denm_codec.cc uppertester_denm_layer.cc endif -ifeq (AtsMapemSpatem, $(ATS)) -sources += uppertester_mapem_spatem_codec.cc uppertester_mapem_spatem_layer.cc + +ifeq (AtsIS, $(ATS)) +sources += uppertester_ivim_codec.cc uppertester_ivim_layer.cc \ + uppertester_mapem_spatem_codec.cc uppertester_mapem_spatem_layer.cc \ + UpperTesterSremSsemCodec.cc UpperTesterSremSsemLayer.cc \ + UpperTesterRtcmemCodec.cc UpperTesterRtcmemLayer.cc endif + ifeq (AtsPki, $(ATS)) sources += uppertester_pki_codec.cc uppertester_pki_layer.cc uppertester_cam_codec.cc endif -ifeq (AtsSremSsem, $(ATS)) -sources += UpperTesterSremSsemCodec.cc UpperTesterSremSsemLayer.cc -endif -ifeq (AtsRtcmem, $(ATS)) -sources += UpperTesterRtcmemCodec.cc UpperTesterRtcmemLayer.cc -endif -ifeq (AtsDENM, $(ATS)) -sources += uppertester_denm_codec.cc uppertester_denm_layer.cc -endif ifeq (AtsSecurity, $(ATS)) sources += uppertester_cam_codec.cc uppertester_cam_layer.cc \ diff --git a/ccsrc/Protocols/UpperTester/uppertester_cam_codec.cc b/ccsrc/Protocols/UpperTester/uppertester_cam_codec.cc index 3fb5b0b33238f1b9108266ff9a26118eda76518c..3c2ec693c4878c714b644d449e0de5b332340ed3 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_cam_codec.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_cam_codec.cc @@ -1,290 +1,290 @@ -#include -//#include - -#include "loggers.hh" -#include "uppertester_cam_codec.hh" - -#include "LibItsCam_TypesAndValues.hh" - -#include "cam_codec.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char uppertester_cam_codec::c_utCamInitialize = 0x00; -unsigned char uppertester_cam_codec::c_utCamInitializeResult = 0x01; -unsigned char uppertester_cam_codec::c_utCamChangePosition = 0x02; -unsigned char uppertester_cam_codec::c_utCamChangePositionResult = 0x03; -unsigned char uppertester_cam_codec::c_utCamChangeCurvature = 0x30; -unsigned char uppertester_cam_codec::c_utCamChangeSpeed = 0x31; -unsigned char uppertester_cam_codec::c_utCamSetAccelerationStatus = 0x32; -unsigned char uppertester_cam_codec::c_utCamSetExteriorLightsStatus = 0x33; -unsigned char uppertester_cam_codec::c_utCamChangeHeading = 0x34; -unsigned char uppertester_cam_codec::c_utCamSetDriveDirection = 0x35; -unsigned char uppertester_cam_codec::c_utCamChangeYawRate = 0x36; -unsigned char uppertester_cam_codec::c_utCamSetStationType = 0x39; -unsigned char uppertester_cam_codec::c_utCamSetVehicleRole = 0x3a; -unsigned char uppertester_cam_codec::c_utCamSetEmbarkationStatus = 0x3b; -unsigned char uppertester_cam_codec::c_utCamSetPtActivation = 0x3c; -unsigned char uppertester_cam_codec::c_utCamSetDangerousGoods = 0x3d; -unsigned char uppertester_cam_codec::c_utCamSetLightBarSirene = 0x3f; -unsigned char uppertester_cam_codec::c_utCamTriggerResult = 0x21; -unsigned char uppertester_cam_codec::c_utCamEventInd = 0x23; - -int uppertester_cam_codec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_cam_codec::encode: ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamInitialize") == 0) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamInitialize)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamChangePosition") == 0) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangePosition)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().warning("<<< uppertester_cam_codec::encode: Failed to encode UT message"); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< uppertester_cam_codec::encode: data=", data); - return 0; -} - -int uppertester_cam_codec::encode(const LibItsCam__TypesAndValues::UtCamTrigger &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_cam_codec::encode: ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - // const Record_Type *type; - const LibItsCam__TypesAndValues::UtCamTrigger &u = static_cast(msg); - if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeCurvature)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeCurvature)); - encoding_buffer.put_string(int2oct(u.changeCurvature(), 2)); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeSpeed)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeSpeed)); - encoding_buffer.put_string(int2oct(u.changeSpeed(), 2)); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setAccelerationControlStatus)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetAccelerationStatus)); - // Convert into ASN.1 encoded format - unsigned char c = *static_cast(u.setAccelerationControlStatus()); - unsigned char r = 0x00; - for (int i = 0; i < 8; i++, c >>= 1) { // TODO Try to refine the reverse bit operation - r = (r << 1) | (c & 0x01); - } // End of 'for' statement - encoding_buffer.put_c(r); - // encoding_buffer.put_c(*static_cast(u.setAccelerationControlStatus())); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setExteriorLightsStatus)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetExteriorLightsStatus)); - // Convert into ASN.1 encoded format - unsigned char c = *static_cast(u.setExteriorLightsStatus()); - unsigned char r = 0x00; - for (int i = 0; i < 8; i++, c >>= 1) { // TODO Try to refine the reverse bit operation - r = (r << 1) | (c & 0x01); - } // End of 'for' statement - encoding_buffer.put_c(r); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeHeading)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeHeading)); - encoding_buffer.put_string(int2oct(u.changeHeading(), 2)); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setDriveDirection)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetDriveDirection)); - encoding_buffer.put_c((unsigned char)static_cast(u.setDriveDirection()).as_int()); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeYawRate)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeYawRate)); - const short i = u.changeYawRate(); - const unsigned char t[2] = {(unsigned char)((i & 0xff00) >> 8), (unsigned char)(i & 0x00ff)}; - OCTETSTRING os(2, t); - encoding_buffer.put_string(os); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setStationType)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetStationType)); - encoding_buffer.put_string(int2oct(u.setStationType(), 1)); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setVehicleRole)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetVehicleRole)); - encoding_buffer.put_c((unsigned char)static_cast(u.setVehicleRole()).as_int()); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setEmbarkationStatus)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetEmbarkationStatus)); - encoding_buffer.put_c((u.setEmbarkationStatus() == true) ? 0xff : 0x00); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setDangerousGoods)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetDangerousGoods)); - encoding_buffer.put_c((unsigned char)static_cast(u.setDangerousGoods()).as_int()); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setPtActivation)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetPtActivation)); - encoding_buffer.put_c(static_cast(u.setPtActivation().ptActivationType())); - const OCTETSTRING &os = u.setPtActivation().ptActivationData(); - encoding_buffer.put_c(static_cast(os.lengthof())); - encoding_buffer.put_string(os); - } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setLightBarSirene)) { - encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetLightBarSirene)); - loggers::get_instance().log("uppertester_cam_codec::encode: BarSirene=0x%02x - 0x%02x", *static_cast(u.setLightBarSirene()), - *static_cast(u.setLightBarSirene()) << 6); - encoding_buffer.put_c(*static_cast(u.setLightBarSirene()) << 6); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().warning("<<< uppertester_cam_codec::encode: Failed to encode UT message"); - return -1; - } - // encode_(*type, *type->get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< uppertester_cam_codec::encode: data=", data); - return 0; -} - -int uppertester_cam_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> uppertester_cam_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, - dynamic_cast(&type)); - loggers::get_instance().log_msg(">>> uppertester_cam_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("uppertester_cam_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("uppertester_cam_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("uppertester_cam_codec::encode_: -1 result code returned"); - return -1; - } - } else if (std::string(r.fld_name(i)).compare("alacarte") == 0) { - // Add empty field length - loggers::get_instance().log("uppertester_cam_codec::encode_: alacarte is missing, add 0x00"); - encoding_buffer.put_c(0x00); - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - loggers::get_instance().log("uppertester_cam_codec::encode_: field to process %s", s.c_str()); - if ((s.rfind(".shape") != string::npos) || (s.rfind(".relevanceDistance") != string::npos) || (s.rfind(".relevanceTrafficDirection") != string::npos)) { - encoding_buffer.put_c((unsigned char)static_cast(type).as_int()); - } else if (s.rfind(".payload") != string::npos) { - const OCTETSTRING & os = static_cast(type); - const unsigned char s[] = {(unsigned char)((os.lengthof() & 0x0000FF00) >> 8), (unsigned char)os.lengthof()}; - encoding_buffer.put_s(2, s); - if (os.lengthof() != 0) { - encoding_buffer.put_string(os); - } - } else if (s.rfind(".detectionTime") != string::npos) { - unsigned long long llu = static_cast(type).get_long_long_val(); - loggers::get_instance().log("uppertester_cam_codec::encode_ : detectionTime=%llu", llu); - std::vector v; - for (int i = 0; i < 6; i++) { - v.insert(v.begin(), static_cast(llu)); - llu >>= 8; - } // End of 'for' statement - OCTETSTRING os(v.size(), v.data()); - loggers::get_instance().log_msg("uppertester_cam_codec::encode_: timeDetection=", os); - encoding_buffer.put_string(os); - } else if ((s.rfind(".validityDuration") != string::npos) || (s.rfind(".repetitionDuration") != string::npos)) { - if (type.is_present()) { - const OPTIONAL &o = dynamic_cast &>(type); - const INTEGER & i = static_cast(*o.get_opt_value()); - loggers::get_instance().log_msg("uppertester_cam_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 3)); - } - } else if ((s.rfind(".informationQuality") != string::npos) || (s.rfind(".causeCode") != string::npos) || (s.rfind(".subCauseCode") != string::npos)) { - const INTEGER &i = static_cast(type); - encoding_buffer.put_string(int2oct(i, 1)); - } else if ((s.rfind(".linkedCause") != string::npos) || (s.rfind(".eventHistory") != string::npos)) { - // Skip them - } else if ((s.rfind(".transmissionInterval") != string::npos) || (s.rfind(".repetitionInterval") != string::npos)) { - if (type.is_present()) { - const OPTIONAL &o = dynamic_cast &>(type); - const INTEGER & i = static_cast(*o.get_opt_value()); - encoding_buffer.put_string(int2oct(i, 2)); - } - } else if (s.rfind(".originatingStationID") != string::npos) { - const INTEGER &i = static_cast(type); - encoding_buffer.put_string(int2oct(i, 4)); - } else if (s.rfind(".sequenceNumber") != string::npos) { - const INTEGER &i = static_cast(type); - encoding_buffer.put_string(int2oct(i, 2)); - } else if (s.rfind(".AlacarteContainer") != string::npos) { - const OPTIONAL &o = dynamic_cast &>(type); - const OCTETSTRING & os = static_cast(*o.get_opt_value()); - encoding_buffer.put_string(int2oct(os.lengthof(), 2)); - encoding_buffer.put_string(os); - } else { - loggers::get_instance().log("uppertester_cam_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - } - - loggers::get_instance().log_to_hexa("<<>> uppertester_cam_codec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< uppertester_cam_codec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr uppertester_cam_codec::decode(const OCTETSTRING &data, params *params) { - - std::unique_ptr result; - - const unsigned char *ptr = static_cast(data); - if (*ptr != uppertester_cam_codec::c_utCamEventInd) { - LibItsCam__TypesAndValues::UtCamResults res; - if (decode(data, res, params) == 0) { - result.reset((Base_Type *)res.clone()); - } else { - result.reset(nullptr); - } - } else { - LibItsCam__TypesAndValues::UtCamEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } - - return result; -} - -int uppertester_cam_codec::decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamResults &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_cam_codec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == uppertester_cam_codec::c_utCamInitializeResult) { - msg.utCamInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_cam_codec::c_utCamChangePositionResult) { - msg.utCamChangePositionResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_cam_codec::c_utCamTriggerResult) { - msg.utCamTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" - // Peer does not support the command - msg.utCamInitializeResult() = 0x00; - } else { - loggers::get_instance().warning("uppertester_cam_codec::decode: Unsupported result"); - return -1; - } - - loggers::get_instance().log_msg("<<< uppertester_cam_codec::decode", msg); - return 0; -} - -int uppertester_cam_codec::decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamEventInd &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_cam_codec::decode (1): decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data) + 1; - OCTETSTRING os(2, ptr); - const unsigned int length = (const unsigned int)((*ptr << 8 & 0xff00) | *(ptr + 1)); - ptr += 2; - loggers::get_instance().log("uppertester_cam_codec::decode (1): CAM message length=%d", length); - if (data.lengthof() - 3 != (const int)length) { - loggers::get_instance().warning("uppertester_cam_codec::decode (1) (4): Wrong payload length: %d", length); - return -1; - } - os = OCTETSTRING(length, ptr); - loggers::get_instance().log_to_hexa("uppertester_cam_codec::decode (1): CAM message=", os); - cam_codec codec; - codec.decode(os, msg.camMsg(), params); - - loggers::get_instance().log_msg("<<< uppertester_cam_codec::decode (1)", msg); - return 0; -} +#include +//#include + +#include "loggers.hh" +#include "uppertester_cam_codec.hh" + +#include "LibItsCam_TypesAndValues.hh" + +#include "cam_codec.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char uppertester_cam_codec::c_utCamInitialize = 0x00; +unsigned char uppertester_cam_codec::c_utCamInitializeResult = 0x01; +unsigned char uppertester_cam_codec::c_utCamChangePosition = 0x02; +unsigned char uppertester_cam_codec::c_utCamChangePositionResult = 0x03; +unsigned char uppertester_cam_codec::c_utCamChangeCurvature = 0x30; +unsigned char uppertester_cam_codec::c_utCamChangeSpeed = 0x31; +unsigned char uppertester_cam_codec::c_utCamSetAccelerationStatus = 0x32; +unsigned char uppertester_cam_codec::c_utCamSetExteriorLightsStatus = 0x33; +unsigned char uppertester_cam_codec::c_utCamChangeHeading = 0x34; +unsigned char uppertester_cam_codec::c_utCamSetDriveDirection = 0x35; +unsigned char uppertester_cam_codec::c_utCamChangeYawRate = 0x36; +unsigned char uppertester_cam_codec::c_utCamSetStationType = 0x39; +unsigned char uppertester_cam_codec::c_utCamSetVehicleRole = 0x3a; +unsigned char uppertester_cam_codec::c_utCamSetEmbarkationStatus = 0x3b; +unsigned char uppertester_cam_codec::c_utCamSetPtActivation = 0x3c; +unsigned char uppertester_cam_codec::c_utCamSetDangerousGoods = 0x3d; +unsigned char uppertester_cam_codec::c_utCamSetLightBarSirene = 0x3f; +unsigned char uppertester_cam_codec::c_utCamTriggerResult = 0x21; +unsigned char uppertester_cam_codec::c_utCamEventInd = 0x23; + +int uppertester_cam_codec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_cam_codec::encode: ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamInitialize") == 0) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamInitialize)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsCam_TypesAndValues.UtCamChangePosition") == 0) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangePosition)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().warning("<<< uppertester_cam_codec::encode: Failed to encode UT message"); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< uppertester_cam_codec::encode: data=", data); + return 0; +} + +int uppertester_cam_codec::encode(const LibItsCam__TypesAndValues::UtCamTrigger &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_cam_codec::encode: ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + // const Record_Type *type; + const LibItsCam__TypesAndValues::UtCamTrigger &u = static_cast(msg); + if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeCurvature)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeCurvature)); + encoding_buffer.put_string(int2oct(u.changeCurvature(), 2)); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeSpeed)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeSpeed)); + encoding_buffer.put_string(int2oct(u.changeSpeed(), 2)); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setAccelerationControlStatus)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetAccelerationStatus)); + // Convert into ASN.1 encoded format + unsigned char c = *static_cast(u.setAccelerationControlStatus()); + unsigned char r = 0x00; + for (int i = 0; i < 8; i++, c >>= 1) { // TODO Try to refine the reverse bit operation + r = (r << 1) | (c & 0x01); + } // End of 'for' statement + encoding_buffer.put_c(r); + // encoding_buffer.put_c(*static_cast(u.setAccelerationControlStatus())); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setExteriorLightsStatus)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetExteriorLightsStatus)); + // Convert into ASN.1 encoded format + unsigned char c = *static_cast(u.setExteriorLightsStatus()); + unsigned char r = 0x00; + for (int i = 0; i < 8; i++, c >>= 1) { // TODO Try to refine the reverse bit operation + r = (r << 1) | (c & 0x01); + } // End of 'for' statement + encoding_buffer.put_c(r); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeHeading)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeHeading)); + encoding_buffer.put_string(int2oct(u.changeHeading(), 2)); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setDriveDirection)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetDriveDirection)); + encoding_buffer.put_c((unsigned char)static_cast(u.setDriveDirection()).as_int()); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_changeYawRate)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamChangeYawRate)); + const short i = u.changeYawRate(); + const unsigned char t[2] = {(unsigned char)((i & 0xff00) >> 8), (unsigned char)(i & 0x00ff)}; + OCTETSTRING os(2, t); + encoding_buffer.put_string(os); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setStationType)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetStationType)); + encoding_buffer.put_string(int2oct(u.setStationType(), 1)); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setVehicleRole)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetVehicleRole)); + encoding_buffer.put_c((unsigned char)static_cast(u.setVehicleRole()).as_int()); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setEmbarkationStatus)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetEmbarkationStatus)); + encoding_buffer.put_c((u.setEmbarkationStatus() == true) ? 0xff : 0x00); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setDangerousGoods)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetDangerousGoods)); + encoding_buffer.put_c((unsigned char)static_cast(u.setDangerousGoods()).as_int()); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setPtActivation)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetPtActivation)); + encoding_buffer.put_c(static_cast(u.setPtActivation().ptActivationType())); + const OCTETSTRING &os = u.setPtActivation().ptActivationData(); + encoding_buffer.put_c(static_cast(os.lengthof())); + encoding_buffer.put_string(os); + } else if (u.ischosen(LibItsCam__TypesAndValues::UtCamTrigger::ALT_setLightBarSirene)) { + encoding_buffer.put_c(static_cast(uppertester_cam_codec::c_utCamSetLightBarSirene)); + loggers::get_instance().log("uppertester_cam_codec::encode: BarSirene=0x%02x - 0x%02x", *static_cast(u.setLightBarSirene()), + *static_cast(u.setLightBarSirene()) << 6); + encoding_buffer.put_c(*static_cast(u.setLightBarSirene()) << 6); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().warning("<<< uppertester_cam_codec::encode: Failed to encode UT message"); + return -1; + } + // encode_(*type, *type->get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< uppertester_cam_codec::encode: data=", data); + return 0; +} + +int uppertester_cam_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> uppertester_cam_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, + dynamic_cast(&type)); + loggers::get_instance().log_msg(">>> uppertester_cam_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("uppertester_cam_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("uppertester_cam_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("uppertester_cam_codec::encode_: -1 result code returned"); + return -1; + } + } else if (std::string(r.fld_name(i)).compare("alacarte") == 0) { + // Add empty field length + loggers::get_instance().log("uppertester_cam_codec::encode_: alacarte is missing, add 0x00"); + encoding_buffer.put_c(0x00); + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + loggers::get_instance().log("uppertester_cam_codec::encode_: field to process %s", s.c_str()); + if ((s.rfind(".shape") != string::npos) || (s.rfind(".relevanceDistance") != string::npos) || (s.rfind(".relevanceTrafficDirection") != string::npos)) { + encoding_buffer.put_c((unsigned char)static_cast(type).as_int()); + } else if (s.rfind(".payload") != string::npos) { + const OCTETSTRING & os = static_cast(type); + const unsigned char s[] = {(unsigned char)((os.lengthof() & 0x0000FF00) >> 8), (unsigned char)os.lengthof()}; + encoding_buffer.put_s(2, s); + if (os.lengthof() != 0) { + encoding_buffer.put_string(os); + } + } else if (s.rfind(".detectionTime") != string::npos) { + unsigned long long llu = static_cast(type).get_long_long_val(); + loggers::get_instance().log("uppertester_cam_codec::encode_ : detectionTime=%llu", llu); + std::vector v; + for (int i = 0; i < 6; i++) { + v.insert(v.begin(), static_cast(llu)); + llu >>= 8; + } // End of 'for' statement + OCTETSTRING os(v.size(), v.data()); + loggers::get_instance().log_msg("uppertester_cam_codec::encode_: timeDetection=", os); + encoding_buffer.put_string(os); + } else if ((s.rfind(".validityDuration") != string::npos) || (s.rfind(".repetitionDuration") != string::npos)) { + if (type.is_present()) { + const OPTIONAL &o = dynamic_cast &>(type); + const INTEGER & i = static_cast(*o.get_opt_value()); + loggers::get_instance().log_msg("uppertester_cam_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 3)); + } + } else if ((s.rfind(".informationQuality") != string::npos) || (s.rfind(".causeCode") != string::npos) || (s.rfind(".subCauseCode") != string::npos)) { + const INTEGER &i = static_cast(type); + encoding_buffer.put_string(int2oct(i, 1)); + } else if ((s.rfind(".linkedCause") != string::npos) || (s.rfind(".eventHistory") != string::npos)) { + // Skip them + } else if ((s.rfind(".transmissionInterval") != string::npos) || (s.rfind(".repetitionInterval") != string::npos)) { + if (type.is_present()) { + const OPTIONAL &o = dynamic_cast &>(type); + const INTEGER & i = static_cast(*o.get_opt_value()); + encoding_buffer.put_string(int2oct(i, 2)); + } + } else if (s.rfind(".originatingStationID") != string::npos) { + const INTEGER &i = static_cast(type); + encoding_buffer.put_string(int2oct(i, 4)); + } else if (s.rfind(".sequenceNumber") != string::npos) { + const INTEGER &i = static_cast(type); + encoding_buffer.put_string(int2oct(i, 2)); + } else if (s.rfind(".AlacarteContainer") != string::npos) { + const OPTIONAL &o = dynamic_cast &>(type); + const OCTETSTRING & os = static_cast(*o.get_opt_value()); + encoding_buffer.put_string(int2oct(os.lengthof(), 2)); + encoding_buffer.put_string(os); + } else { + loggers::get_instance().log("uppertester_cam_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + } + + loggers::get_instance().log_to_hexa("<<>> uppertester_cam_codec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< uppertester_cam_codec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr uppertester_cam_codec::decode(const OCTETSTRING &data, params *params) { + + std::unique_ptr result; + + const unsigned char *ptr = static_cast(data); + if (*ptr != uppertester_cam_codec::c_utCamEventInd) { + LibItsCam__TypesAndValues::UtCamResults res; + if (decode(data, res, params) == 0) { + result.reset((Base_Type *)res.clone()); + } else { + result.reset(nullptr); + } + } else { + LibItsCam__TypesAndValues::UtCamEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } + + return result; +} + +int uppertester_cam_codec::decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamResults &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_cam_codec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == uppertester_cam_codec::c_utCamInitializeResult) { + msg.utCamInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_cam_codec::c_utCamChangePositionResult) { + msg.utCamChangePositionResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_cam_codec::c_utCamTriggerResult) { + msg.utCamTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" + // Peer does not support the command + msg.utCamInitializeResult() = 0x00; + } else { + loggers::get_instance().warning("uppertester_cam_codec::decode: Unsupported result"); + return -1; + } + + loggers::get_instance().log_msg("<<< uppertester_cam_codec::decode", msg); + return 0; +} + +int uppertester_cam_codec::decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamEventInd &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_cam_codec::decode (1): decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data) + 1; + OCTETSTRING os(2, ptr); + const unsigned int length = (const unsigned int)((*ptr << 8 & 0xff00) | *(ptr + 1)); + ptr += 2; + loggers::get_instance().log("uppertester_cam_codec::decode (1): CAM message length=%d", length); + if (data.lengthof() - 3 != (const int)length) { + loggers::get_instance().warning("uppertester_cam_codec::decode (1) (4): Wrong payload length: %d", length); + return -1; + } + os = OCTETSTRING(length, ptr); + loggers::get_instance().log_to_hexa("uppertester_cam_codec::decode (1): CAM message=", os); + cam_codec codec; + codec.decode(os, msg.camMsg(), params); + + loggers::get_instance().log_msg("<<< uppertester_cam_codec::decode (1)", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/uppertester_cam_codec.hh b/ccsrc/Protocols/UpperTester/uppertester_cam_codec.hh index f6e3816705d44d1be54fc8303b798b9c1b86ec8d..ccb50515b45734513ff3c281b825507a26e3fc53 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_cam_codec.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_cam_codec.hh @@ -1,66 +1,66 @@ -/*! - * \file uppertester_cam_codec.hh - * \brief Header file for ITS UpperTester CAM codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsCam__TypesAndValues { - class UtCamTrigger; - class UtCamResults; - class UtCamEventInd; -} // namespace LibItsCam__TypesAndValues - -class uppertester_cam_codec : public codec { -public: - static unsigned char c_utCamInitialize; - static unsigned char c_utCamInitializeResult; - static unsigned char c_utCamChangePosition; - static unsigned char c_utCamChangePositionResult; - static unsigned char c_utCamChangeCurvature; - static unsigned char c_utCamChangeSpeed; - static unsigned char c_utCamSetAccelerationStatus; - static unsigned char c_utCamSetExteriorLightsStatus; - static unsigned char c_utCamChangeHeading; - static unsigned char c_utCamSetDriveDirection; - static unsigned char c_utCamChangeYawRate; - static unsigned char c_utCamSetStationType; - static unsigned char c_utCamSetVehicleRole; - static unsigned char c_utCamSetEmbarkationStatus; - static unsigned char c_utCamSetPtActivation; - static unsigned char c_utCamSetDangerousGoods; - static unsigned char c_utCamSetLightBarSirene; - static unsigned char c_utCamTriggerResult; - static unsigned char c_utCamEventInd; - -private: - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - uppertester_cam_codec() : codec(){}; - virtual ~uppertester_cam_codec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - int encode(const LibItsCam__TypesAndValues::UtCamTrigger &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamEventInd &msg, params *params = NULL); -}; // End of class uppertester_cam_codec +/*! + * \file uppertester_cam_codec.hh + * \brief Header file for ITS UpperTester CAM codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsCam__TypesAndValues { + class UtCamTrigger; + class UtCamResults; + class UtCamEventInd; +} // namespace LibItsCam__TypesAndValues + +class uppertester_cam_codec : public codec { +public: + static unsigned char c_utCamInitialize; + static unsigned char c_utCamInitializeResult; + static unsigned char c_utCamChangePosition; + static unsigned char c_utCamChangePositionResult; + static unsigned char c_utCamChangeCurvature; + static unsigned char c_utCamChangeSpeed; + static unsigned char c_utCamSetAccelerationStatus; + static unsigned char c_utCamSetExteriorLightsStatus; + static unsigned char c_utCamChangeHeading; + static unsigned char c_utCamSetDriveDirection; + static unsigned char c_utCamChangeYawRate; + static unsigned char c_utCamSetStationType; + static unsigned char c_utCamSetVehicleRole; + static unsigned char c_utCamSetEmbarkationStatus; + static unsigned char c_utCamSetPtActivation; + static unsigned char c_utCamSetDangerousGoods; + static unsigned char c_utCamSetLightBarSirene; + static unsigned char c_utCamTriggerResult; + static unsigned char c_utCamEventInd; + +private: + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + uppertester_cam_codec() : codec(){}; + virtual ~uppertester_cam_codec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + int encode(const LibItsCam__TypesAndValues::UtCamTrigger &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsCam__TypesAndValues::UtCamEventInd &msg, params *params = NULL); +}; // End of class uppertester_cam_codec diff --git a/ccsrc/Protocols/UpperTester/uppertester_cam_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_cam_layer.cc index d3bef14d32ff94d1eb5277bddb0f0a155498a6a1..9bb509f805054e5e9b5e58341843c13bc1513043 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_cam_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_cam_layer.cc @@ -1,83 +1,83 @@ -#include "uppertester_cam_layer_factory.hh" - -#include "LibItsCam_TestSystem.hh" -#include "LibItsCam_TypesAndValues.hh" - -#include "loggers.hh" - -uppertester_cam_layer::uppertester_cam_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> uppertester_cam_layer::uppertester_cam_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - params::const_iterator it = _params.find(params::loopback); - if (it == _params.cend()) { - _params.insert(std::pair(params::loopback, "0")); - } -} - -void uppertester_cam_layer::sendMsg(const LibItsCam__TypesAndValues::UtCamInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_cam_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsCam__TypesAndValues::UtCamResults ut_cam_results; - ut_cam_results.utCamInitializeResult() = BOOLEAN(true); - to_all_upper_ports(ut_cam_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_cam_layer::sendMsg(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_cam_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsCam__TypesAndValues::UtCamResults ut_cam_results; - ut_cam_results.utCamChangePositionResult() = BOOLEAN(true); - to_all_upper_ports(ut_cam_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_cam_layer::sendMsg(const LibItsCam__TypesAndValues::UtCamTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_cam_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsCam__TypesAndValues::UtCamResults ut_cam_results; - ut_cam_results.utCamTriggerResult() = BOOLEAN(true); - to_all_upper_ports(ut_cam_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_cam_layer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_cam_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void uppertester_cam_layer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_cam_layer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -uppertester_cam_layer_factory uppertester_cam_layer_factory::_f; +#include "uppertester_cam_layer_factory.hh" + +#include "LibItsCam_TestSystem.hh" +#include "LibItsCam_TypesAndValues.hh" + +#include "loggers.hh" + +uppertester_cam_layer::uppertester_cam_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> uppertester_cam_layer::uppertester_cam_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + params::const_iterator it = _params.find(params::loopback); + if (it == _params.cend()) { + _params.insert(std::pair(params::loopback, "0")); + } +} + +void uppertester_cam_layer::sendMsg(const LibItsCam__TypesAndValues::UtCamInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_cam_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsCam__TypesAndValues::UtCamResults ut_cam_results; + ut_cam_results.utCamInitializeResult() = BOOLEAN(true); + to_all_upper_ports(ut_cam_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_cam_layer::sendMsg(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_cam_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsCam__TypesAndValues::UtCamResults ut_cam_results; + ut_cam_results.utCamChangePositionResult() = BOOLEAN(true); + to_all_upper_ports(ut_cam_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_cam_layer::sendMsg(const LibItsCam__TypesAndValues::UtCamTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_cam_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsCam__TypesAndValues::UtCamResults ut_cam_results; + ut_cam_results.utCamTriggerResult() = BOOLEAN(true); + to_all_upper_ports(ut_cam_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_cam_layer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_cam_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void uppertester_cam_layer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_cam_layer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +uppertester_cam_layer_factory uppertester_cam_layer_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_cam_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_cam_layer.hh index e61c45345f035fdc5402674f2c194364eef13652..90ab4dd5c0e7825484e7b06360279ee10cb7ccac 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_cam_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_cam_layer.hh @@ -1,43 +1,43 @@ -/*! - * \file uppertester_cam_layer.hh - * \brief Header file for ITS UpperTester CAM protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "t_layer.hh" -#include "uppertester_cam_codec.hh" - -namespace LibItsCam__TestSystem { - class UpperTesterPort; -} - -namespace LibItsCam__TypesAndValues { - class UtCamInitialize; - class UtCamChangePosition; - class UtCamTrigger; -} // namespace LibItsCam__TypesAndValues - -class uppertester_cam_layer : public t_layer { - params _params; - uppertester_cam_codec _codec; - -public: - uppertester_cam_layer() : t_layer(), _params(), _codec(){}; - uppertester_cam_layer(const std::string &p_type, const std::string ¶m); - virtual ~uppertester_cam_layer(){}; - - void sendMsg(const LibItsCam__TypesAndValues::UtCamInitialize &send_par, params &p_params); - void sendMsg(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par, params &p_params); - void sendMsg(const LibItsCam__TypesAndValues::UtCamTrigger &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class uppertester_cam_layer +/*! + * \file uppertester_cam_layer.hh + * \brief Header file for ITS UpperTester CAM protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "t_layer.hh" +#include "uppertester_cam_codec.hh" + +namespace LibItsCam__TestSystem { + class UpperTesterPort; +} + +namespace LibItsCam__TypesAndValues { + class UtCamInitialize; + class UtCamChangePosition; + class UtCamTrigger; +} // namespace LibItsCam__TypesAndValues + +class uppertester_cam_layer : public t_layer { + params _params; + uppertester_cam_codec _codec; + +public: + uppertester_cam_layer() : t_layer(), _params(), _codec(){}; + uppertester_cam_layer(const std::string &p_type, const std::string ¶m); + virtual ~uppertester_cam_layer(){}; + + void sendMsg(const LibItsCam__TypesAndValues::UtCamInitialize &send_par, params &p_params); + void sendMsg(const LibItsCam__TypesAndValues::UtCamChangePosition &send_par, params &p_params); + void sendMsg(const LibItsCam__TypesAndValues::UtCamTrigger &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class uppertester_cam_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_cam_layer_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_cam_layer_factory.hh index 522900e0eeb782eac3c9b75164bde95386e8fa13..cd9c95412347a018cbfa8929bce98d112a22cc71 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_cam_layer_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_cam_layer_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file uppertester_cam_layer_factory.hh - * \brief Header file for ITS CAM Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_cam_layer.hh" - -class uppertester_cam_layer_factory : public layer_factory { - static uppertester_cam_layer_factory _f; - -public: - uppertester_cam_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_CAM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_cam_layer(p_type, p_param); }; -}; // End of class uppertester_cam_layer_factory +/*! + * \file uppertester_cam_layer_factory.hh + * \brief Header file for ITS CAM Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_cam_layer.hh" + +class uppertester_cam_layer_factory : public layer_factory { + static uppertester_cam_layer_factory _f; + +public: + uppertester_cam_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_CAM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_cam_layer(p_type, p_param); }; +}; // End of class uppertester_cam_layer_factory diff --git a/ccsrc/Protocols/UpperTester/uppertester_debug_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_debug_layer.cc index e4bd9e8724d0f9ecbb6cc0408e34229f8e198248..d858c1e1dcb1c558ebc2531a4b1dc797858565d1 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_debug_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_debug_layer.cc @@ -1,50 +1,50 @@ -#include - -#include - -#include "loggers.hh" - -#include "uppertester_debug_layer_factory.hh" - -uppertester_debug_layer::uppertester_debug_layer(const std::string &p_type, const std::string ¶m) : layer(p_type), PORT(p_type.c_str()), _params() { - loggers::get_instance().log(">>> uppertester_debug_layer::uppertester_debug_layer: %s, %s", to_string().c_str(), param.c_str()); - - // Setup parameters - params::convert(_params, param); -} - -uppertester_debug_layer::~uppertester_debug_layer() { loggers::get_instance().log(">>> uppertester_debug_layer::~uppertester_debug_layer"); } - -void uppertester_debug_layer::send_data(OCTETSTRING &p_data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_debug_layer::send_data: ", p_data); - - receive_data(p_data, p_params); -} - -void uppertester_debug_layer::receive_data(OCTETSTRING &p_data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_debug_layer::receive_data: ", p_data); - - OCTETSTRING data; - if (p_data[0].get_octet() == 0x00) { // UtInitialize - data = int2oct(257, 2); // '0101'O - } else if (p_data[0].get_octet() == 0x02) { // UtChangePosition - data = int2oct(769, 2); // '0301'O - } else if (p_data[0].get_octet() == 0x04) { // UtChangePseudonym - data = int2oct(1281, 2); // '0501'O - } else if (p_data[0].get_octet() == 0x10) { // UtDenmTrigger - data = int2oct(4353, 2) + int2oct(1234, 2); // '110104D2'O - } else if (p_data[0].get_octet() == 0x12) { // UtDenmUpdate - data = int2oct(4609, 2) + int2oct(1234, 2); // '110104D2'O - } else if (p_data[0].get_octet() == 0x14) { // UtDenmTermination - // '15xxxx'O - } else if ((p_data[0].get_octet() >= 0x30) && (p_data[0].get_octet() <= 0x3f)) { - // UtCamTrigger - data = int2oct(8449, 2); // '2101'O - } else { - data = int2oct(256, 2); // '0100'O - } - - receive_to_all_layers(data, p_params); -} - -uppertester_debug_layer_factory uppertester_debug_layer_factory::_f; +#include + +#include + +#include "loggers.hh" + +#include "uppertester_debug_layer_factory.hh" + +uppertester_debug_layer::uppertester_debug_layer(const std::string &p_type, const std::string ¶m) : layer(p_type), PORT(p_type.c_str()), _params() { + loggers::get_instance().log(">>> uppertester_debug_layer::uppertester_debug_layer: %s, %s", to_string().c_str(), param.c_str()); + + // Setup parameters + params::convert(_params, param); +} + +uppertester_debug_layer::~uppertester_debug_layer() { loggers::get_instance().log(">>> uppertester_debug_layer::~uppertester_debug_layer"); } + +void uppertester_debug_layer::send_data(OCTETSTRING &p_data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_debug_layer::send_data: ", p_data); + + receive_data(p_data, p_params); +} + +void uppertester_debug_layer::receive_data(OCTETSTRING &p_data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_debug_layer::receive_data: ", p_data); + + OCTETSTRING data; + if (p_data[0].get_octet() == 0x00) { // UtInitialize + data = int2oct(257, 2); // '0101'O + } else if (p_data[0].get_octet() == 0x02) { // UtChangePosition + data = int2oct(769, 2); // '0301'O + } else if (p_data[0].get_octet() == 0x04) { // UtChangePseudonym + data = int2oct(1281, 2); // '0501'O + } else if (p_data[0].get_octet() == 0x10) { // UtDenmTrigger + data = int2oct(4353, 2) + int2oct(1234, 2); // '110104D2'O + } else if (p_data[0].get_octet() == 0x12) { // UtDenmUpdate + data = int2oct(4609, 2) + int2oct(1234, 2); // '110104D2'O + } else if (p_data[0].get_octet() == 0x14) { // UtDenmTermination + // '15xxxx'O + } else if ((p_data[0].get_octet() >= 0x30) && (p_data[0].get_octet() <= 0x3f)) { + // UtCamTrigger + data = int2oct(8449, 2); // '2101'O + } else { + data = int2oct(256, 2); // '0100'O + } + + receive_to_all_layers(data, p_params); +} + +uppertester_debug_layer_factory uppertester_debug_layer_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_debug_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_debug_layer.hh index 626c120b305056120a6a3ff8ab71cad9ab0e0b11..6fa59f950501e03eedbc92c6c1a0f60199ee834f 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_debug_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_debug_layer.hh @@ -1,60 +1,60 @@ -/*! - * \file uppertester_debug_layer.hh - * \brief Header file for ITS UPPERTESTER_DEBUG/IP protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include - -#include "params.hh" -#include "t_layer.hh" - -class PORT; //! Forward declaration of TITAN class - -/*! - * \class uppertester_debug_layer - * \brief This class provides description of ITS UPPERTESTER_DEBUG/IP protocol layer - */ -class uppertester_debug_layer : public layer, public PORT { - params _params; //! Layer parameters - -public: //! \publicsection - /*! - * \brief Specialised constructor - * Create a new instance of the uppertester_debug_layer class - * \param[in] p_type \todo - * \param[in] p_param \todo - */ - uppertester_debug_layer(const std::string &p_type, const std::string &p_param); - /*! - * \brief Default destructor - */ - virtual ~uppertester_debug_layer(); - - /*! - * \virtual - * \fn void send_data(OCTETSTRING& data, params& params); - * \brief Send bytes formated data to the lower layers - * \param[in] p_data The data to be sent - * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters - */ - virtual void send_data(OCTETSTRING &p_data, params &p_params); - /*! - * \virtual - * \fn void receive_data(OCTETSTRING& data, params& params); - * \brief Receive bytes formated data from the lower layers - * \param[in] p_data The bytes formated data received - * \param[in] p_params Some lower layers parameters values when data was received - */ - virtual void receive_data(OCTETSTRING &p_data, params &p_params); - -}; // End of class uppertester_debug_layer +/*! + * \file uppertester_debug_layer.hh + * \brief Header file for ITS UPPERTESTER_DEBUG/IP protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include + +#include "params.hh" +#include "t_layer.hh" + +class PORT; //! Forward declaration of TITAN class + +/*! + * \class uppertester_debug_layer + * \brief This class provides description of ITS UPPERTESTER_DEBUG/IP protocol layer + */ +class uppertester_debug_layer : public layer, public PORT { + params _params; //! Layer parameters + +public: //! \publicsection + /*! + * \brief Specialised constructor + * Create a new instance of the uppertester_debug_layer class + * \param[in] p_type \todo + * \param[in] p_param \todo + */ + uppertester_debug_layer(const std::string &p_type, const std::string &p_param); + /*! + * \brief Default destructor + */ + virtual ~uppertester_debug_layer(); + + /*! + * \virtual + * \fn void send_data(OCTETSTRING& data, params& params); + * \brief Send bytes formated data to the lower layers + * \param[in] p_data The data to be sent + * \param[in] p_params Some parameters to overwrite default value of the lower layers parameters + */ + virtual void send_data(OCTETSTRING &p_data, params &p_params); + /*! + * \virtual + * \fn void receive_data(OCTETSTRING& data, params& params); + * \brief Receive bytes formated data from the lower layers + * \param[in] p_data The bytes formated data received + * \param[in] p_params Some lower layers parameters values when data was received + */ + virtual void receive_data(OCTETSTRING &p_data, params &p_params); + +}; // End of class uppertester_debug_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_debug_layer_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_debug_layer_factory.hh index f67af45c8d72ed924b3b33ebe391afbdee2c4d19..4ec53c65c7ace13935d622cbb5b227755d989773 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_debug_layer_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_debug_layer_factory.hh @@ -1,42 +1,42 @@ -/*! - * \file uppertester_debug_layer_factory.hh - * \brief Header file for ITS UpperTester Debug protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved.o - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_debug_layer.hh" - -/*! - * \class uppertester_debug_layer_factory - * \brief This class provides a factory class to create an uppertester_debug_layer class instance - */ -class uppertester_debug_layer_factory : public layer_factory { - static uppertester_debug_layer_factory _f; //! Reference to the unique instance of this class -public: //! \publicsection - /*! - * \brief Default constructor - * Create a new instance of the uppertester_debug_layer_factory class - * \remark The UPPERTESTER_DEBUG/IP layer identifier is UPPERTESTER_DEBUG - */ - uppertester_debug_layer_factory() { - // register factory - layer_stack_builder::register_layer_factory("DEBUG", this); - }; - /*! - * \fn layer* create_layer(const std::string & type, const std::string & param); - * \brief Create the layers stack based on the provided layers stack description - * \param[in] p_type The provided layers stack description - * \param[in] p_params Optional parameters - * \return 0 on success, -1 otherwise - * \inline - */ - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_debug_layer(p_type, p_param); }; -}; // End of class uppertester_debug_layer_factory +/*! + * \file uppertester_debug_layer_factory.hh + * \brief Header file for ITS UpperTester Debug protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved.o + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_debug_layer.hh" + +/*! + * \class uppertester_debug_layer_factory + * \brief This class provides a factory class to create an uppertester_debug_layer class instance + */ +class uppertester_debug_layer_factory : public layer_factory { + static uppertester_debug_layer_factory _f; //! Reference to the unique instance of this class +public: //! \publicsection + /*! + * \brief Default constructor + * Create a new instance of the uppertester_debug_layer_factory class + * \remark The UPPERTESTER_DEBUG/IP layer identifier is UPPERTESTER_DEBUG + */ + uppertester_debug_layer_factory() { + // register factory + layer_stack_builder::register_layer_factory("DEBUG", this); + }; + /*! + * \fn layer* create_layer(const std::string & type, const std::string & param); + * \brief Create the layers stack based on the provided layers stack description + * \param[in] p_type The provided layers stack description + * \param[in] p_params Optional parameters + * \return 0 on success, -1 otherwise + * \inline + */ + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_debug_layer(p_type, p_param); }; +}; // End of class uppertester_debug_layer_factory diff --git a/ccsrc/Protocols/UpperTester/uppertester_denm_codec.cc b/ccsrc/Protocols/UpperTester/uppertester_denm_codec.cc index 05f48b3b0e045d97ec3efdf46e3903b53847e059..b69f9087d52438471aae34249fc4ccce230d6906 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_denm_codec.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_denm_codec.cc @@ -1,300 +1,300 @@ -#include -//#include - -#include "loggers.hh" -#include "uppertester_denm_codec.hh" - -#include "LibItsDenm_TestSystem.hh" -#include "LibItsDenm_TypesAndValues.hh" - -#include "denm_codec.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char uppertester_denm_codec::c_utDenmInitialize = 0x00; -unsigned char uppertester_denm_codec::c_utDenmInitializeResult = 0x01; -unsigned char uppertester_denm_codec::c_utDenmChangePosition = 0x02; -unsigned char uppertester_denm_codec::c_utDenmChangePositionResult = 0x03; -unsigned char uppertester_denm_codec::c_utDenmChangePseudonym = 0x04; -unsigned char uppertester_denm_codec::c_utDenmChangePseudonymResult = 0x05; -unsigned char uppertester_denm_codec::c_utDenmTrigger = 0x10; -unsigned char uppertester_denm_codec::c_utDenmTriggerResult = 0x11; -unsigned char uppertester_denm_codec::c_utDenmUpdate = 0x12; -unsigned char uppertester_denm_codec::c_utDenmUpdateResult = 0x13; -unsigned char uppertester_denm_codec::c_utDenmTermination = 0x14; -unsigned char uppertester_denm_codec::c_utDenmTerminationResult = 0x15; -unsigned char uppertester_denm_codec::c_utDenmEventIndication = 0x17; - -int uppertester_denm_codec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_denm_codec::encode: ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmInitialize") == 0) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmInitialize)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmChangePosition") == 0) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmChangePosition)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmChangePseudonym") == 0) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmChangePseudonym)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmTrigger") == 0) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmTrigger)); - // See ETSI TR 103 099 V1.4.1 Clause C.4.1 GenerateDenmEvent - unsigned char flags = 0x00; - const LibItsDenm__TypesAndValues::UtDenmTrigger &r = static_cast(msg); - if (r.validityDuration().is_present()) { // V - flags |= 0x80; - } - if (r.repetitionDuration().is_present()) { // R - flags |= 0x40; - } - if (r.relevanceTrafficDirection().is_present()) { // T - flags |= 0x10; - } - if (r.transmissionInterval().is_present()) { // K - flags |= 0x04; - } - if (r.repetitionInterval().is_present()) { // I - flags |= 0x02; - } - encoding_buffer.put_c(flags); - loggers::get_instance().log_to_hexa("uppertester_denm_codec::encode: flags=", encoding_buffer); - // Continue with encoding - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmUpdate") == 0) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmUpdate)); - // See ETSI TR 103 099 V1.3.21 (20152016-07) Clause C.4.1GenerateDenmEvent - unsigned char flags = 0x00; - const LibItsDenm__TypesAndValues::UtDenmUpdate &r = static_cast(msg); - if (r.validityDuration().is_present()) { // V - flags |= 0x80; - } - if (r.situation().is_present()) { // S - flags |= 0x40; - } - if (r.relevanceDistance().is_present()) { // D - flags |= 0x20; - } - if (r.relevanceTrafficDirection().is_present()) { // T - flags |= 0x10; - } - // TODO Check TTCN-3 code, it's missing - /*if (r.trafficClass().is_present()) { // C - flags |= 0x08; - }*/ - if (r.transmissionInterval().is_present()) { // K - flags |= 0x04; - } - if (r.repetitionInterval().is_present()) { // I - flags |= 0x02; - } - encoding_buffer.put_c(flags); - loggers::get_instance().log_to_hexa("uppertester_denm_codec::encode: flags=", encoding_buffer); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmTermination") == 0) { - encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmTermination)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().warning("<<< uppertester_denm_codec::encode: Failed to encode UT message"); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< uppertester_denm_codec::encode: data=", data); - return 0; -} - -int uppertester_denm_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> uppertester_denm_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, - dynamic_cast(&type)); - loggers::get_instance().log_msg(">>> uppertester_denm_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("uppertester_denm_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("uppertester_denm_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("uppertester_denm_codec::encode_: -1 result code returned"); - return -1; - } - } else { - std::string s(r.fld_descr(i)->name); - if ((s.rfind(".validityDuration") != string::npos) || (s.rfind(".repetitionDuration") != string::npos) || - (s.rfind(".situation") != string::npos)) { // Pad with three bytes - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - } else if ((s.rfind(".transmissionInterval") != string::npos) || (s.rfind(".repetitionInterval") != string::npos)) { // Pad with two bytes - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - } else if ((s.rfind(".informationQuality") != string::npos) || (s.rfind(".relevanceTrafficDirection") != string::npos) || - (s.rfind(".relevanceDistance") != string::npos) // Mandatory in DenmTrigger, optional in DenmUpdate - ) { // Pad with one byte - encoding_buffer.put_c((unsigned char)0x00); - } else if (std::string(r.fld_name(i)).compare("alacarte") == 0) { - // Add empty field length - loggers::get_instance().log("uppertester_denm_codec::encode_: alacarte is missing, add 0x00"); - encoding_buffer.put_c(0x00); - } - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - loggers::get_instance().log("uppertester_denm_codec::encode_: field to process %s", s.c_str()); - if ((s.rfind(".shape") != string::npos) || (s.rfind(".relevanceDistance") != string::npos) || (s.rfind(".relevanceTrafficDirection") != string::npos)) { - encoding_buffer.put_c((unsigned char)static_cast(type).as_int()); - } else if (s.rfind(".payload") != string::npos) { - const OCTETSTRING & os = static_cast(type); - const unsigned char s[] = {(unsigned char)((os.lengthof() & 0x0000FF00) >> 8), (unsigned char)os.lengthof()}; - encoding_buffer.put_s(2, s); - if (os.lengthof() != 0) { - encoding_buffer.put_string(os); - } - } else if (s.rfind(".detectionTime") != string::npos) { - unsigned long long llu = static_cast(type).get_long_long_val(); - loggers::get_instance().log("uppertester_denm_codec::encode_ : detectionTime=%llu", llu); - std::vector v; - for (int i = 0; i < 6; i++) { - v.insert(v.begin(), static_cast(llu)); - llu >>= 8; - } // End of 'for' statement - OCTETSTRING os(v.size(), v.data()); - loggers::get_instance().log_msg("uppertester_denm_codec::encode_: timeDetection=", os); - encoding_buffer.put_string(os); - } else if ((s.rfind(".validityDuration") != string::npos) || (s.rfind(".repetitionDuration") != string::npos)) { - const OPTIONAL &o = dynamic_cast &>(type); - const INTEGER & i = static_cast(*o.get_opt_value()); - loggers::get_instance().log_msg("uppertester_denm_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 3)); - } else if ((s.rfind(".causeCode") != string::npos) || (s.rfind(".subCauseCode") != string::npos) || (s.rfind(".informationQuality") != string::npos) || - (s.rfind(".relevanceDistance") != string::npos)) { - const INTEGER &i = static_cast(type); - loggers::get_instance().log("uppertester_denm_codec::encode_: o=%02x", *static_cast(int2oct(i, 1))); - encoding_buffer.put_c(*static_cast(int2oct(i, 1))); - } else if ((s.rfind(".linkedCause") != string::npos) || (s.rfind(".eventHistory") != string::npos)) { - // Skip them - } else if ((s.rfind(".transmissionInterval") != string::npos) || (s.rfind(".repetitionInterval") != string::npos)) { - const OPTIONAL &o = dynamic_cast &>(type); - const INTEGER & i = static_cast(*o.get_opt_value()); - encoding_buffer.put_string(int2oct(i, 2)); - } else if (s.rfind(".originatingStationID") != string::npos) { - const INTEGER &i = static_cast(type); - loggers::get_instance().log_msg("uppertester_denm_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 4)); - } else if (s.rfind(".sequenceNumber") != string::npos) { - const INTEGER &i = static_cast(type); - loggers::get_instance().log_msg("uppertester_denm_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 2)); - } else if (s.rfind(".situation") != string::npos) { - const OPTIONAL &o = dynamic_cast &>(type); - const DENM__PDU__Descriptions::SituationContainer & bt = static_cast(*o.get_opt_value()); - encode_(bt, field_descriptor, encoding_buffer); - } else if (s.rfind(".AlacarteContainer") != string::npos) { - const OPTIONAL &o = dynamic_cast &>(type); - const OCTETSTRING & os = static_cast(*o.get_opt_value()); - loggers::get_instance().log_msg("uppertester_denm_codec::encode_: os=", int2oct(os.lengthof(), 1)); - encoding_buffer.put_string(int2oct(os.lengthof(), 1)); - loggers::get_instance().log_msg("uppertester_denm_codec::encode_: os=", os); - encoding_buffer.put_string(os); - } else { - loggers::get_instance().log("uppertester_denm_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - } - - loggers::get_instance().log_to_hexa("<<< uppertester_denm_codec::encode_: encoding_buffer=", encoding_buffer); - return 0; -} - -int uppertester_denm_codec::decode(const OCTETSTRING &data, Record_Type &msg, params *params) { - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - - loggers::get_instance().log_to_hexa(">>> uppertester_denm_codec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< uppertester_denm_codec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr uppertester_denm_codec::decode(const OCTETSTRING &data, params *params) { - - std::unique_ptr result; - - const unsigned char *ptr = static_cast(data); - if (*ptr != uppertester_denm_codec::c_utDenmEventIndication) { - LibItsDenm__TypesAndValues::UtDenmResults res; - decode(data, res, params); - result.reset((Base_Type *)res.clone()); - } else { - LibItsDenm__TypesAndValues::UtDenmEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } - - return result; -} - -int uppertester_denm_codec::decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmResults &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_denm_codec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == uppertester_denm_codec::c_utDenmInitializeResult) { - msg.utDenmInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_denm_codec::c_utDenmChangePositionResult) { - msg.utDenmChangePositionResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_denm_codec::c_utDenmChangePseudonymResult) { - msg.utDenmChangePseudonymResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_denm_codec::c_utDenmTerminationResult) { - msg.utDenmTerminationResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_denm_codec::c_utDenmTriggerResult) { - LibItsDenm__TypesAndValues::UtDenmTriggerResult r; - ptr += 1; - r.result() = BOOLEAN(*ptr == 0x01); - ptr += 1; - OCTETSTRING os(4, ptr); - ptr += 4; - r.actionId().originatingStationID() = oct2int(os); - os = OCTETSTRING(2, ptr); - r.actionId().sequenceNumber() = oct2int(os); - msg.utDenmTriggerResult() = r; - } else if (*ptr == uppertester_denm_codec::c_utDenmUpdateResult) { - LibItsDenm__TypesAndValues::UtDenmUpdateResult r; - ptr += 1; - r.result() = BOOLEAN(*ptr == 0x01); - ptr += 1; - OCTETSTRING os(4, ptr); - ptr += 4; - r.actionId().originatingStationID() = oct2int(os); - os = OCTETSTRING(2, ptr); - r.actionId().sequenceNumber() = oct2int(os); - msg.utDenmUpdateResult() = r; - } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" - // Peer does not support the command - msg.utDenmInitializeResult() = 0x00; - } else { - loggers::get_instance().warning("uppertester_denm_codec::decode: Unsupported result"); - } - - loggers::get_instance().log_msg("<<< uppertester_denm_codec::decode", msg); - return 0; -} - -int uppertester_denm_codec::decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmEventInd &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_denm_codec::decode (1): decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data) + 1; - OCTETSTRING os(2, ptr); - ptr += 2; - unsigned int length = oct2int(os); - loggers::get_instance().log("uppertester_denm_codec::decode (1): DENM message length=%d", length); - os = OCTETSTRING(length, ptr); - loggers::get_instance().log_to_hexa("uppertester_denm_codec::decode (1): DENM message=", os); - denm_codec codec; - codec.decode(os, msg.denMsg(), params); - - loggers::get_instance().log_msg("<<< uppertester_denm_codec::decode (1)", msg); - return 0; -} +#include +//#include + +#include "loggers.hh" +#include "uppertester_denm_codec.hh" + +#include "LibItsDenm_TestSystem.hh" +#include "LibItsDenm_TypesAndValues.hh" + +#include "denm_codec.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char uppertester_denm_codec::c_utDenmInitialize = 0x00; +unsigned char uppertester_denm_codec::c_utDenmInitializeResult = 0x01; +unsigned char uppertester_denm_codec::c_utDenmChangePosition = 0x02; +unsigned char uppertester_denm_codec::c_utDenmChangePositionResult = 0x03; +unsigned char uppertester_denm_codec::c_utDenmChangePseudonym = 0x04; +unsigned char uppertester_denm_codec::c_utDenmChangePseudonymResult = 0x05; +unsigned char uppertester_denm_codec::c_utDenmTrigger = 0x10; +unsigned char uppertester_denm_codec::c_utDenmTriggerResult = 0x11; +unsigned char uppertester_denm_codec::c_utDenmUpdate = 0x12; +unsigned char uppertester_denm_codec::c_utDenmUpdateResult = 0x13; +unsigned char uppertester_denm_codec::c_utDenmTermination = 0x14; +unsigned char uppertester_denm_codec::c_utDenmTerminationResult = 0x15; +unsigned char uppertester_denm_codec::c_utDenmEventIndication = 0x17; + +int uppertester_denm_codec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_denm_codec::encode: ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmInitialize") == 0) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmInitialize)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmChangePosition") == 0) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmChangePosition)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmChangePseudonym") == 0) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmChangePseudonym)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmTrigger") == 0) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmTrigger)); + // See ETSI TR 103 099 V1.4.1 Clause C.4.1 GenerateDenmEvent + unsigned char flags = 0x00; + const LibItsDenm__TypesAndValues::UtDenmTrigger &r = static_cast(msg); + if (r.validityDuration().is_present()) { // V + flags |= 0x80; + } + if (r.repetitionDuration().is_present()) { // R + flags |= 0x40; + } + if (r.relevanceTrafficDirection().is_present()) { // T + flags |= 0x10; + } + if (r.transmissionInterval().is_present()) { // K + flags |= 0x04; + } + if (r.repetitionInterval().is_present()) { // I + flags |= 0x02; + } + encoding_buffer.put_c(flags); + loggers::get_instance().log_to_hexa("uppertester_denm_codec::encode: flags=", encoding_buffer); + // Continue with encoding + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmUpdate") == 0) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmUpdate)); + // See ETSI TR 103 099 V1.3.21 (20152016-07) Clause C.4.1GenerateDenmEvent + unsigned char flags = 0x00; + const LibItsDenm__TypesAndValues::UtDenmUpdate &r = static_cast(msg); + if (r.validityDuration().is_present()) { // V + flags |= 0x80; + } + if (r.situation().is_present()) { // S + flags |= 0x40; + } + if (r.relevanceDistance().is_present()) { // D + flags |= 0x20; + } + if (r.relevanceTrafficDirection().is_present()) { // T + flags |= 0x10; + } + // TODO Check TTCN-3 code, it's missing + /*if (r.trafficClass().is_present()) { // C + flags |= 0x08; + }*/ + if (r.transmissionInterval().is_present()) { // K + flags |= 0x04; + } + if (r.repetitionInterval().is_present()) { // I + flags |= 0x02; + } + encoding_buffer.put_c(flags); + loggers::get_instance().log_to_hexa("uppertester_denm_codec::encode: flags=", encoding_buffer); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsDenm_TypesAndValues.UtDenmTermination") == 0) { + encoding_buffer.put_c(static_cast(uppertester_denm_codec::c_utDenmTermination)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().warning("<<< uppertester_denm_codec::encode: Failed to encode UT message"); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< uppertester_denm_codec::encode: data=", data); + return 0; +} + +int uppertester_denm_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> uppertester_denm_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, + dynamic_cast(&type)); + loggers::get_instance().log_msg(">>> uppertester_denm_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("uppertester_denm_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("uppertester_denm_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("uppertester_denm_codec::encode_: -1 result code returned"); + return -1; + } + } else { + std::string s(r.fld_descr(i)->name); + if ((s.rfind(".validityDuration") != string::npos) || (s.rfind(".repetitionDuration") != string::npos) || + (s.rfind(".situation") != string::npos)) { // Pad with three bytes + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + } else if ((s.rfind(".transmissionInterval") != string::npos) || (s.rfind(".repetitionInterval") != string::npos)) { // Pad with two bytes + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + } else if ((s.rfind(".informationQuality") != string::npos) || (s.rfind(".relevanceTrafficDirection") != string::npos) || + (s.rfind(".relevanceDistance") != string::npos) // Mandatory in DenmTrigger, optional in DenmUpdate + ) { // Pad with one byte + encoding_buffer.put_c((unsigned char)0x00); + } else if (std::string(r.fld_name(i)).compare("alacarte") == 0) { + // Add empty field length + loggers::get_instance().log("uppertester_denm_codec::encode_: alacarte is missing, add 0x00"); + encoding_buffer.put_c(0x00); + } + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + loggers::get_instance().log("uppertester_denm_codec::encode_: field to process %s", s.c_str()); + if ((s.rfind(".shape") != string::npos) || (s.rfind(".relevanceDistance") != string::npos) || (s.rfind(".relevanceTrafficDirection") != string::npos)) { + encoding_buffer.put_c((unsigned char)static_cast(type).as_int()); + } else if (s.rfind(".payload") != string::npos) { + const OCTETSTRING & os = static_cast(type); + const unsigned char s[] = {(unsigned char)((os.lengthof() & 0x0000FF00) >> 8), (unsigned char)os.lengthof()}; + encoding_buffer.put_s(2, s); + if (os.lengthof() != 0) { + encoding_buffer.put_string(os); + } + } else if (s.rfind(".detectionTime") != string::npos) { + unsigned long long llu = static_cast(type).get_long_long_val(); + loggers::get_instance().log("uppertester_denm_codec::encode_ : detectionTime=%llu", llu); + std::vector v; + for (int i = 0; i < 6; i++) { + v.insert(v.begin(), static_cast(llu)); + llu >>= 8; + } // End of 'for' statement + OCTETSTRING os(v.size(), v.data()); + loggers::get_instance().log_msg("uppertester_denm_codec::encode_: timeDetection=", os); + encoding_buffer.put_string(os); + } else if ((s.rfind(".validityDuration") != string::npos) || (s.rfind(".repetitionDuration") != string::npos)) { + const OPTIONAL &o = dynamic_cast &>(type); + const INTEGER & i = static_cast(*o.get_opt_value()); + loggers::get_instance().log_msg("uppertester_denm_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 3)); + } else if ((s.rfind(".causeCode") != string::npos) || (s.rfind(".subCauseCode") != string::npos) || (s.rfind(".informationQuality") != string::npos) || + (s.rfind(".relevanceDistance") != string::npos)) { + const INTEGER &i = static_cast(type); + loggers::get_instance().log("uppertester_denm_codec::encode_: o=%02x", *static_cast(int2oct(i, 1))); + encoding_buffer.put_c(*static_cast(int2oct(i, 1))); + } else if ((s.rfind(".linkedCause") != string::npos) || (s.rfind(".eventHistory") != string::npos)) { + // Skip them + } else if ((s.rfind(".transmissionInterval") != string::npos) || (s.rfind(".repetitionInterval") != string::npos)) { + const OPTIONAL &o = dynamic_cast &>(type); + const INTEGER & i = static_cast(*o.get_opt_value()); + encoding_buffer.put_string(int2oct(i, 2)); + } else if (s.rfind(".originatingStationID") != string::npos) { + const INTEGER &i = static_cast(type); + loggers::get_instance().log_msg("uppertester_denm_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 4)); + } else if (s.rfind(".sequenceNumber") != string::npos) { + const INTEGER &i = static_cast(type); + loggers::get_instance().log_msg("uppertester_denm_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 2)); + } else if (s.rfind(".situation") != string::npos) { + const OPTIONAL &o = dynamic_cast &>(type); + const DENM__PDU__Descriptions::SituationContainer & bt = static_cast(*o.get_opt_value()); + encode_(bt, field_descriptor, encoding_buffer); + } else if (s.rfind(".AlacarteContainer") != string::npos) { + const OPTIONAL &o = dynamic_cast &>(type); + const OCTETSTRING & os = static_cast(*o.get_opt_value()); + loggers::get_instance().log_msg("uppertester_denm_codec::encode_: os=", int2oct(os.lengthof(), 1)); + encoding_buffer.put_string(int2oct(os.lengthof(), 1)); + loggers::get_instance().log_msg("uppertester_denm_codec::encode_: os=", os); + encoding_buffer.put_string(os); + } else { + loggers::get_instance().log("uppertester_denm_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + } + + loggers::get_instance().log_to_hexa("<<< uppertester_denm_codec::encode_: encoding_buffer=", encoding_buffer); + return 0; +} + +int uppertester_denm_codec::decode(const OCTETSTRING &data, Record_Type &msg, params *params) { + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + + loggers::get_instance().log_to_hexa(">>> uppertester_denm_codec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< uppertester_denm_codec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr uppertester_denm_codec::decode(const OCTETSTRING &data, params *params) { + + std::unique_ptr result; + + const unsigned char *ptr = static_cast(data); + if (*ptr != uppertester_denm_codec::c_utDenmEventIndication) { + LibItsDenm__TypesAndValues::UtDenmResults res; + decode(data, res, params); + result.reset((Base_Type *)res.clone()); + } else { + LibItsDenm__TypesAndValues::UtDenmEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } + + return result; +} + +int uppertester_denm_codec::decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmResults &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_denm_codec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == uppertester_denm_codec::c_utDenmInitializeResult) { + msg.utDenmInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_denm_codec::c_utDenmChangePositionResult) { + msg.utDenmChangePositionResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_denm_codec::c_utDenmChangePseudonymResult) { + msg.utDenmChangePseudonymResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_denm_codec::c_utDenmTerminationResult) { + msg.utDenmTerminationResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_denm_codec::c_utDenmTriggerResult) { + LibItsDenm__TypesAndValues::UtDenmTriggerResult r; + ptr += 1; + r.result() = BOOLEAN(*ptr == 0x01); + ptr += 1; + OCTETSTRING os(4, ptr); + ptr += 4; + r.actionId().originatingStationID() = oct2int(os); + os = OCTETSTRING(2, ptr); + r.actionId().sequenceNumber() = oct2int(os); + msg.utDenmTriggerResult() = r; + } else if (*ptr == uppertester_denm_codec::c_utDenmUpdateResult) { + LibItsDenm__TypesAndValues::UtDenmUpdateResult r; + ptr += 1; + r.result() = BOOLEAN(*ptr == 0x01); + ptr += 1; + OCTETSTRING os(4, ptr); + ptr += 4; + r.actionId().originatingStationID() = oct2int(os); + os = OCTETSTRING(2, ptr); + r.actionId().sequenceNumber() = oct2int(os); + msg.utDenmUpdateResult() = r; + } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" + // Peer does not support the command + msg.utDenmInitializeResult() = 0x00; + } else { + loggers::get_instance().warning("uppertester_denm_codec::decode: Unsupported result"); + } + + loggers::get_instance().log_msg("<<< uppertester_denm_codec::decode", msg); + return 0; +} + +int uppertester_denm_codec::decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmEventInd &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_denm_codec::decode (1): decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data) + 1; + OCTETSTRING os(2, ptr); + ptr += 2; + unsigned int length = oct2int(os); + loggers::get_instance().log("uppertester_denm_codec::decode (1): DENM message length=%d", length); + os = OCTETSTRING(length, ptr); + loggers::get_instance().log_to_hexa("uppertester_denm_codec::decode (1): DENM message=", os); + denm_codec codec; + codec.decode(os, msg.denMsg(), params); + + loggers::get_instance().log_msg("<<< uppertester_denm_codec::decode (1)", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/uppertester_denm_codec.hh b/ccsrc/Protocols/UpperTester/uppertester_denm_codec.hh index 397b90df9a843138e2d3255d2be7d6c4b27571a9..839504b62d0e95a72ab4e25c7c035175d15b48f9 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_denm_codec.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_denm_codec.hh @@ -1,57 +1,57 @@ -/*! - * \file uppertester_denm_codec.hh - * \brief Header file for ITS UpperTester DENM codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsDenm__TypesAndValues { - class UtDenmResults; - class UtDenmEventInd; -} // namespace LibItsDenm__TypesAndValues - -class uppertester_denm_codec : public codec { -public: - static unsigned char c_utDenmInitialize; - static unsigned char c_utDenmInitializeResult; - static unsigned char c_utDenmChangePosition; - static unsigned char c_utDenmChangePositionResult; - static unsigned char c_utDenmChangePseudonym; - static unsigned char c_utDenmChangePseudonymResult; - static unsigned char c_utDenmTrigger; - static unsigned char c_utDenmTriggerResult; - static unsigned char c_utDenmUpdate; - static unsigned char c_utDenmUpdateResult; - static unsigned char c_utDenmTermination; - static unsigned char c_utDenmTerminationResult; - static unsigned char c_utDenmEventIndication; - - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - uppertester_denm_codec() : codec(){}; - virtual ~uppertester_denm_codec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmEventInd &msg, params *params = NULL); -}; // End of class uppertester_denm_codec +/*! + * \file uppertester_denm_codec.hh + * \brief Header file for ITS UpperTester DENM codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsDenm__TypesAndValues { + class UtDenmResults; + class UtDenmEventInd; +} // namespace LibItsDenm__TypesAndValues + +class uppertester_denm_codec : public codec { +public: + static unsigned char c_utDenmInitialize; + static unsigned char c_utDenmInitializeResult; + static unsigned char c_utDenmChangePosition; + static unsigned char c_utDenmChangePositionResult; + static unsigned char c_utDenmChangePseudonym; + static unsigned char c_utDenmChangePseudonymResult; + static unsigned char c_utDenmTrigger; + static unsigned char c_utDenmTriggerResult; + static unsigned char c_utDenmUpdate; + static unsigned char c_utDenmUpdateResult; + static unsigned char c_utDenmTermination; + static unsigned char c_utDenmTerminationResult; + static unsigned char c_utDenmEventIndication; + + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + uppertester_denm_codec() : codec(){}; + virtual ~uppertester_denm_codec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsDenm__TypesAndValues::UtDenmEventInd &msg, params *params = NULL); +}; // End of class uppertester_denm_codec diff --git a/ccsrc/Protocols/UpperTester/uppertester_denm_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_denm_layer.cc index 6ee111fb279b504801ea6b8891719151add0784b..4611aa955272870b9175713b81c45b62621a326e 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_denm_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_denm_layer.cc @@ -1,138 +1,138 @@ -#include "uppertester_denm_layer_factory.hh" - -#include "LibItsDenm_TestSystem.hh" -#include "LibItsDenm_TypesAndValues.hh" - -#include "loggers.hh" - -uppertester_denm_layer::uppertester_denm_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> uppertester_denm_layer::uppertester_denm_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - - params::const_iterator it = _params.find(params::loopback); - if (it == _params.cend()) { - _params.insert(std::pair(params::loopback, "0")); - } - it = _params.find(params::station_id); - if (it == _params.cend()) { - _params.insert(std::pair(params::station_id, "12345")); - } -} // End of ctor - -void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; - ut_denm_results.utDenmInitializeResult() = BOOLEAN(true); - to_all_upper_ports(ut_denm_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; - ut_denm_results.utDenmChangePositionResult() = BOOLEAN(true); - to_all_upper_ports(ut_denm_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; - ut_denm_results.utDenmChangePseudonymResult() = BOOLEAN(true); - to_all_upper_ports(ut_denm_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsDenm__TypesAndValues::UtDenmTriggerResult trigger_result(true, ITS__Container::ActionID(std::stoi(_params[params::station_id]), 1)); - LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; - ut_denm_results.utDenmTriggerResult() = trigger_result; - to_all_upper_ports(ut_denm_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsDenm__TypesAndValues::UtDenmUpdateResult update_result(true, ITS__Container::ActionID(std::stoi(_params[params::station_id]), 1)); - LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; - ut_denm_results.utDenmUpdateResult() = update_result; - to_all_upper_ports(ut_denm_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; - ut_denm_results.utDenmTerminationResult() = BOOLEAN(true); - to_all_upper_ports(ut_denm_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_denm_layer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void uppertester_denm_layer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_denm_layer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -uppertester_denm_layer_factory uppertester_denm_layer_factory::_f; +#include "uppertester_denm_layer_factory.hh" + +#include "LibItsDenm_TestSystem.hh" +#include "LibItsDenm_TypesAndValues.hh" + +#include "loggers.hh" + +uppertester_denm_layer::uppertester_denm_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> uppertester_denm_layer::uppertester_denm_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + + params::const_iterator it = _params.find(params::loopback); + if (it == _params.cend()) { + _params.insert(std::pair(params::loopback, "0")); + } + it = _params.find(params::station_id); + if (it == _params.cend()) { + _params.insert(std::pair(params::station_id, "12345")); + } +} // End of ctor + +void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; + ut_denm_results.utDenmInitializeResult() = BOOLEAN(true); + to_all_upper_ports(ut_denm_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; + ut_denm_results.utDenmChangePositionResult() = BOOLEAN(true); + to_all_upper_ports(ut_denm_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; + ut_denm_results.utDenmChangePseudonymResult() = BOOLEAN(true); + to_all_upper_ports(ut_denm_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsDenm__TypesAndValues::UtDenmTriggerResult trigger_result(true, ITS__Container::ActionID(std::stoi(_params[params::station_id]), 1)); + LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; + ut_denm_results.utDenmTriggerResult() = trigger_result; + to_all_upper_ports(ut_denm_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsDenm__TypesAndValues::UtDenmUpdateResult update_result(true, ITS__Container::ActionID(std::stoi(_params[params::station_id]), 1)); + LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; + ut_denm_results.utDenmUpdateResult() = update_result; + to_all_upper_ports(ut_denm_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_denm_layer::sendMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsDenm__TypesAndValues::UtDenmResults ut_denm_results; + ut_denm_results.utDenmTerminationResult() = BOOLEAN(true); + to_all_upper_ports(ut_denm_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_denm_layer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void uppertester_denm_layer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_denm_layer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +uppertester_denm_layer_factory uppertester_denm_layer_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_denm_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_denm_layer.hh index 828742b131886acebf3e42f90c21a84461ccb1ac..94e927fb1c496585eb44b6bf4507945f135d8e88 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_denm_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_denm_layer.hh @@ -1,49 +1,49 @@ -/*! - * \file uppertester_denm_layer.hh - * \brief Header file for ITS UpperTester DENM protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "t_layer.hh" -#include "uppertester_denm_codec.hh" - -namespace LibItsDenm__TestSystem { - class UpperTesterPort; -} - -namespace LibItsDenm__TypesAndValues { - class UtDenmInitialize; - class UtDenmChangePosition; - class UtDenmChangePseudonym; - class UtDenmTrigger; - class UtDenmUpdate; - class UtDenmTermination; -} // namespace LibItsDenm__TypesAndValues - -class uppertester_denm_layer : public t_layer { - params _params; - uppertester_denm_codec _codec; - -public: - uppertester_denm_layer() : t_layer(), _params(), _codec(){}; - uppertester_denm_layer(const std::string &p_type, const std::string ¶m); - virtual ~uppertester_denm_layer(){}; - - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par, params &p_params); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par, params &p_params); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par, params &p_params); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par, params &p_params); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par, params &p_params); - void sendMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class uppertester_denm_layer +/*! + * \file uppertester_denm_layer.hh + * \brief Header file for ITS UpperTester DENM protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "t_layer.hh" +#include "uppertester_denm_codec.hh" + +namespace LibItsDenm__TestSystem { + class UpperTesterPort; +} + +namespace LibItsDenm__TypesAndValues { + class UtDenmInitialize; + class UtDenmChangePosition; + class UtDenmChangePseudonym; + class UtDenmTrigger; + class UtDenmUpdate; + class UtDenmTermination; +} // namespace LibItsDenm__TypesAndValues + +class uppertester_denm_layer : public t_layer { + params _params; + uppertester_denm_codec _codec; + +public: + uppertester_denm_layer() : t_layer(), _params(), _codec(){}; + uppertester_denm_layer(const std::string &p_type, const std::string ¶m); + virtual ~uppertester_denm_layer(){}; + + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmInitialize &send_par, params &p_params); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePosition &send_par, params &p_params); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmChangePseudonym &send_par, params &p_params); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmTrigger &send_par, params &p_params); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmUpdate &send_par, params &p_params); + void sendMsg(const LibItsDenm__TypesAndValues::UtDenmTermination &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class uppertester_denm_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_denm_layer_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_denm_layer_factory.hh index 997717e835b0ab4652be65ef06414284c341694c..3d4e7c404161fc15a862865ce98102dfa96d69bc 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_denm_layer_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_denm_layer_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file uppertester_denm_layer_factory.hh - * \brief Header file for ITS IVIM Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_denm_layer.hh" - -class uppertester_denm_layer_factory : public layer_factory { - static uppertester_denm_layer_factory _f; - -public: - uppertester_denm_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_DENM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_denm_layer(p_type, p_param); }; -}; // End of class uppertester_denm_layer_factory +/*! + * \file uppertester_denm_layer_factory.hh + * \brief Header file for ITS IVIM Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_denm_layer.hh" + +class uppertester_denm_layer_factory : public layer_factory { + static uppertester_denm_layer_factory _f; + +public: + uppertester_denm_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_DENM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_denm_layer(p_type, p_param); }; +}; // End of class uppertester_denm_layer_factory diff --git a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.cc b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.cc index c940e9a92ae088ebf7ac0ba0b6552e23b153ac9e..500330d1552c5abc7bef09d9adf705abc6d7eb97 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.cc @@ -1,197 +1,197 @@ -#include -//#include - -#include "loggers.hh" -#include "uppertester_geonetworking_codec.hh" - -#include "LibItsGeoNetworking_TestSystem.hh" -#include "LibItsGeoNetworking_TypesAndValues.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char uppertester_geonetworking_codec::c_utGnInitialize = 0x00; -unsigned char uppertester_geonetworking_codec::c_utGnInitializeResult = 0x01; -unsigned char uppertester_geonetworking_codec::c_utGnChangePosition = 0x02; -unsigned char uppertester_geonetworking_codec::c_utGnChangePositionResult = 0x03; -unsigned char uppertester_geonetworking_codec::c_utGnTriggerResult = 0x41; -unsigned char uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast = 0x50; -unsigned char uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast = 0x51; -unsigned char uppertester_geonetworking_codec::c_utGnTrigger_GeoAnycast = 0x52; -unsigned char uppertester_geonetworking_codec::c_utGnTrigger_Shb = 0x53; -unsigned char uppertester_geonetworking_codec::c_utGnTrigger_Tsb = 0x54; -unsigned char uppertester_geonetworking_codec::c_utGnEventIndication = 0x55; - -int uppertester_geonetworking_codec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::encode: ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnInitialize") == 0) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnInitialize)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnChangePosition") == 0) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnChangePosition)); - } else { // Error - data = OCTETSTRING(0, nullptr); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - - loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::encode: data=", data); - return 0; -} - -int uppertester_geonetworking_codec::encode(const Base_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log(">>> uppertester_geonetworking_codec::encode: %s", msg.get_descriptor()->name); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - - Base_Type *type = nullptr; - if (std::string(msg.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnTrigger") == 0) { - const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &t = static_cast(msg); - loggers::get_instance().log("uppertester_geonetworking_codec::encode: After cast: %s", t.get_descriptor()->name); - if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_geoUnicast)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast)); - type = (Base_Type *)&(t.geoUnicast()); - } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_geoBroadcast)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast)); - type = (Base_Type *)&(t.geoBroadcast()); - } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_geoAnycast)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_GeoAnycast)); - type = (Base_Type *)&(t.geoAnycast()); - } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_shb)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_Shb)); - type = (Base_Type *)&(t.shb()); - } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_tsb)) { - encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_Tsb)); - type = (Base_Type *)&(t.tsb()); - } // else, nothing to do - } else { - data = OCTETSTRING(0, nullptr); - return -1; - } - encode_(*type, *(type->get_descriptor()), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - - loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::encode: data=", data); - - return 0; -} - -int uppertester_geonetworking_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> uppertester_geonetworking_codec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); - loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("uppertester_geonetworking_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("uppertester_geonetworking_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", - r.fld_name(i), r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), - r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("uppertester_geonetworking_codec::encode_: -1 result code returned"); - return -1; - } - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - if (s.rfind(".shape") != string::npos) { - encoding_buffer.put_c((unsigned char)static_cast(type).as_int()); - } else if (s.rfind(".payload") != string::npos) { - const OCTETSTRING & os = static_cast(type); - const unsigned char s[] = {(unsigned char)((os.lengthof() & 0x0000FF00) >> 8), (unsigned char)os.lengthof()}; - encoding_buffer.put_s(2, s); - if (os.lengthof() != 0) { - encoding_buffer.put_string(os); - } - } else { - loggers::get_instance().log("uppertester_geonetworking_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - } - - loggers::get_instance().log_to_hexa("<<>> uppertester_geonetworking_codec::decode (1): ", data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - - loggers::get_instance().log_to_hexa("uppertester_geonetworking_codec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr uppertester_geonetworking_codec::decode(const OCTETSTRING &data, params *params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::decode (2): ", data); - - std::unique_ptr result; - - const unsigned char *ptr = static_cast(data); - if ((*ptr == uppertester_geonetworking_codec::c_utGnInitializeResult) || (*ptr == uppertester_geonetworking_codec::c_utGnChangePositionResult) || - (*ptr == uppertester_geonetworking_codec::c_utGnTriggerResult)) { - LibItsGeoNetworking__TypesAndValues::UtGnResults res; - decode(data, res, params); - result.reset((Base_Type *)res.clone()); - } else if ((*ptr == uppertester_geonetworking_codec::c_utGnEventIndication)) { - LibItsGeoNetworking__TypesAndValues::UtGnEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } else { - loggers::get_instance().warning("uppertester_geonetworking_codec::decode (2): Unsupported UpperTester command 0x%02x", *ptr); - } - - return result; -} - -int uppertester_geonetworking_codec::decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnResults &msg, params *params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::decode (3): ", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == uppertester_geonetworking_codec::c_utGnInitializeResult) { - msg.utGnInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_geonetworking_codec::c_utGnChangePositionResult) { - msg.utGnChangePositionResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_geonetworking_codec::c_utGnTriggerResult) { - msg.utGnTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" - // Peer does not support the command - msg.utGnInitializeResult() = 0x00; - } else { - loggers::get_instance().warning("uppertester_geonetworking_codec::decode: Unsupported result"); - return -1; - } - - loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::decode", msg); - return 0; -} - -int uppertester_geonetworking_codec::decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnEventInd &msg, params *params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::decode (4): ", data); - - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - - const unsigned int length = (const unsigned int)((data[1].get_octet() << 8 & 0xff00) | data[2].get_octet()); - if (data.lengthof() - 3 != (const int)length) { - loggers::get_instance().warning("uppertester_geonetworking_codec::decode (4): Wrong payload length: %d", length); - return -1; - } - - msg.rawPayload() = OCTETSTRING(length, 3 + static_cast(data)); - - loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::decode (4): ", msg); - return 0; -} +#include +//#include + +#include "loggers.hh" +#include "uppertester_geonetworking_codec.hh" + +#include "LibItsGeoNetworking_TestSystem.hh" +#include "LibItsGeoNetworking_TypesAndValues.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char uppertester_geonetworking_codec::c_utGnInitialize = 0x00; +unsigned char uppertester_geonetworking_codec::c_utGnInitializeResult = 0x01; +unsigned char uppertester_geonetworking_codec::c_utGnChangePosition = 0x02; +unsigned char uppertester_geonetworking_codec::c_utGnChangePositionResult = 0x03; +unsigned char uppertester_geonetworking_codec::c_utGnTriggerResult = 0x41; +unsigned char uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast = 0x50; +unsigned char uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast = 0x51; +unsigned char uppertester_geonetworking_codec::c_utGnTrigger_GeoAnycast = 0x52; +unsigned char uppertester_geonetworking_codec::c_utGnTrigger_Shb = 0x53; +unsigned char uppertester_geonetworking_codec::c_utGnTrigger_Tsb = 0x54; +unsigned char uppertester_geonetworking_codec::c_utGnEventIndication = 0x55; + +int uppertester_geonetworking_codec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::encode: ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnInitialize") == 0) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnInitialize)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnChangePosition") == 0) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnChangePosition)); + } else { // Error + data = OCTETSTRING(0, nullptr); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + + loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::encode: data=", data); + return 0; +} + +int uppertester_geonetworking_codec::encode(const Base_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log(">>> uppertester_geonetworking_codec::encode: %s", msg.get_descriptor()->name); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + + Base_Type *type = nullptr; + if (std::string(msg.get_descriptor()->name).compare("@LibItsGeoNetworking_TypesAndValues.UtGnTrigger") == 0) { + const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &t = static_cast(msg); + loggers::get_instance().log("uppertester_geonetworking_codec::encode: After cast: %s", t.get_descriptor()->name); + if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_geoUnicast)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_GeoUnicast)); + type = (Base_Type *)&(t.geoUnicast()); + } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_geoBroadcast)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_GeoBroadcast)); + type = (Base_Type *)&(t.geoBroadcast()); + } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_geoAnycast)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_GeoAnycast)); + type = (Base_Type *)&(t.geoAnycast()); + } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_shb)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_Shb)); + type = (Base_Type *)&(t.shb()); + } else if (t.ischosen(LibItsGeoNetworking__TypesAndValues::UtGnTrigger::ALT_tsb)) { + encoding_buffer.put_c(static_cast(uppertester_geonetworking_codec::c_utGnTrigger_Tsb)); + type = (Base_Type *)&(t.tsb()); + } // else, nothing to do + } else { + data = OCTETSTRING(0, nullptr); + return -1; + } + encode_(*type, *(type->get_descriptor()), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + + loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::encode: data=", data); + + return 0; +} + +int uppertester_geonetworking_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> uppertester_geonetworking_codec::encode_: processing %s/%s", type.get_descriptor()->name, field_descriptor.name); + loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("uppertester_geonetworking_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("uppertester_geonetworking_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", + r.fld_name(i), r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), + r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("uppertester_geonetworking_codec::encode_: -1 result code returned"); + return -1; + } + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + if (s.rfind(".shape") != string::npos) { + encoding_buffer.put_c((unsigned char)static_cast(type).as_int()); + } else if (s.rfind(".payload") != string::npos) { + const OCTETSTRING & os = static_cast(type); + const unsigned char s[] = {(unsigned char)((os.lengthof() & 0x0000FF00) >> 8), (unsigned char)os.lengthof()}; + encoding_buffer.put_s(2, s); + if (os.lengthof() != 0) { + encoding_buffer.put_string(os); + } + } else { + loggers::get_instance().log("uppertester_geonetworking_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + } + + loggers::get_instance().log_to_hexa("<<>> uppertester_geonetworking_codec::decode (1): ", data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + + loggers::get_instance().log_to_hexa("uppertester_geonetworking_codec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr uppertester_geonetworking_codec::decode(const OCTETSTRING &data, params *params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::decode (2): ", data); + + std::unique_ptr result; + + const unsigned char *ptr = static_cast(data); + if ((*ptr == uppertester_geonetworking_codec::c_utGnInitializeResult) || (*ptr == uppertester_geonetworking_codec::c_utGnChangePositionResult) || + (*ptr == uppertester_geonetworking_codec::c_utGnTriggerResult)) { + LibItsGeoNetworking__TypesAndValues::UtGnResults res; + decode(data, res, params); + result.reset((Base_Type *)res.clone()); + } else if ((*ptr == uppertester_geonetworking_codec::c_utGnEventIndication)) { + LibItsGeoNetworking__TypesAndValues::UtGnEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } else { + loggers::get_instance().warning("uppertester_geonetworking_codec::decode (2): Unsupported UpperTester command 0x%02x", *ptr); + } + + return result; +} + +int uppertester_geonetworking_codec::decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnResults &msg, params *params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::decode (3): ", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == uppertester_geonetworking_codec::c_utGnInitializeResult) { + msg.utGnInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_geonetworking_codec::c_utGnChangePositionResult) { + msg.utGnChangePositionResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_geonetworking_codec::c_utGnTriggerResult) { + msg.utGnTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == 0x24) { // TODO Use a constant for "Peer does not support is "Peer does not support the command" + // Peer does not support the command + msg.utGnInitializeResult() = 0x00; + } else { + loggers::get_instance().warning("uppertester_geonetworking_codec::decode: Unsupported result"); + return -1; + } + + loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::decode", msg); + return 0; +} + +int uppertester_geonetworking_codec::decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnEventInd &msg, params *params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_codec::decode (4): ", data); + + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + + const unsigned int length = (const unsigned int)((data[1].get_octet() << 8 & 0xff00) | data[2].get_octet()); + if (data.lengthof() - 3 != (const int)length) { + loggers::get_instance().warning("uppertester_geonetworking_codec::decode (4): Wrong payload length: %d", length); + return -1; + } + + msg.rawPayload() = OCTETSTRING(length, 3 + static_cast(data)); + + loggers::get_instance().log_msg("<<< uppertester_geonetworking_codec::decode (4): ", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.hh b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.hh index a2d815375b1f66b6ee79f06e34dd56e2d32b9bbf..105b38d452476eeeda1c832a7ff3364c1c46ed80 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_codec.hh @@ -1,57 +1,57 @@ -/*! - * \file uppertester_geonetworking_codec.hh - * \brief Header file for ITS UpperTester GeoNetworking codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsGeoNetworking__TypesAndValues { - class UtGnResults; - class UtGnEventInd; -} // namespace LibItsGeoNetworking__TypesAndValues - -class uppertester_geonetworking_codec : public codec { -public: - static unsigned char c_utGnInitialize; - static unsigned char c_utGnInitializeResult; - static unsigned char c_utGnChangePosition; - static unsigned char c_utGnChangePositionResult; - static unsigned char c_utGnTriggerResult; - static unsigned char c_utGnTrigger_GeoUnicast; - static unsigned char c_utGnTrigger_GeoBroadcast; - static unsigned char c_utGnTrigger_GeoAnycast; - static unsigned char c_utGnTrigger_Shb; - static unsigned char c_utGnTrigger_Tsb; - static unsigned char c_utGnEventIndication; - -private: - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - uppertester_geonetworking_codec() : codec(){}; - virtual ~uppertester_geonetworking_codec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int encode(const Base_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - virtual std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnEventInd &msg, params *params = NULL); -}; // End of class uppertester_geonetworking_codec +/*! + * \file uppertester_geonetworking_codec.hh + * \brief Header file for ITS UpperTester GeoNetworking codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsGeoNetworking__TypesAndValues { + class UtGnResults; + class UtGnEventInd; +} // namespace LibItsGeoNetworking__TypesAndValues + +class uppertester_geonetworking_codec : public codec { +public: + static unsigned char c_utGnInitialize; + static unsigned char c_utGnInitializeResult; + static unsigned char c_utGnChangePosition; + static unsigned char c_utGnChangePositionResult; + static unsigned char c_utGnTriggerResult; + static unsigned char c_utGnTrigger_GeoUnicast; + static unsigned char c_utGnTrigger_GeoBroadcast; + static unsigned char c_utGnTrigger_GeoAnycast; + static unsigned char c_utGnTrigger_Shb; + static unsigned char c_utGnTrigger_Tsb; + static unsigned char c_utGnEventIndication; + +private: + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + uppertester_geonetworking_codec() : codec(){}; + virtual ~uppertester_geonetworking_codec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int encode(const Base_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + virtual std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsGeoNetworking__TypesAndValues::UtGnEventInd &msg, params *params = NULL); +}; // End of class uppertester_geonetworking_codec diff --git a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_factory.hh index b321e26afc75b461114beaf333c1072b8c6822ca..dc0798ecd6019deb567d84c1a146ce4cf1486327 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file uppertester_geonetworking_factory.hh - * \brief Header file for ITS GeoNetworking Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_geonetworking_layer.hh" - -class uppertester_geonetworking_factory : public layer_factory { - static uppertester_geonetworking_factory _f; - -public: - uppertester_geonetworking_factory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_GN", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_geonetworking_layer(p_type, p_param); }; -}; // End of class uppertester_geonetworking_factory +/*! + * \file uppertester_geonetworking_factory.hh + * \brief Header file for ITS GeoNetworking Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_geonetworking_layer.hh" + +class uppertester_geonetworking_factory : public layer_factory { + static uppertester_geonetworking_factory _f; + +public: + uppertester_geonetworking_factory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_GN", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_geonetworking_layer(p_type, p_param); }; +}; // End of class uppertester_geonetworking_factory diff --git a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.cc index df7045788996812f270aff6737b6c880ede0a86b..a4b069d86099ee9d6d221a699f8b35308e0169b8 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.cc @@ -1,98 +1,98 @@ -#include "uppertester_geonetworking_factory.hh" - -#include "LibItsGeoNetworking_TestSystem.hh" -#include "LibItsGeoNetworking_TypesAndValues.hh" - -#include "loggers.hh" - -uppertester_geonetworking_layer::uppertester_geonetworking_layer(const std::string &p_type, const std::string &p_param) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> uppertester_geonetworking_layer::uppertester_geonetworking_layer: %s, %s", to_string().c_str(), p_param.c_str()); - // Setup parameters - params::convert(_params, p_param); - params::const_iterator it = _params.find(params::loopback); - if (it == _params.cend()) { - _params.insert(std::pair(params::loopback, "0")); - } -} - -void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; - ut_gn_results.utGnInitializeResult() = BOOLEAN(true); - to_all_upper_ports(ut_gn_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(static_cast(send_par), data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; - ut_gn_results.utGnChangePositionResult() = BOOLEAN(true); - to_all_upper_ports(ut_gn_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(static_cast(send_par), data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; - ut_gn_results.utGnTriggerResult() = BOOLEAN(true); - to_all_upper_ports(ut_gn_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; - ut_gn_results.utGnTriggerResult() = BOOLEAN(true); - to_all_upper_ports(ut_gn_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_geonetworking_layer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void uppertester_geonetworking_layer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::receive_data: ", data); - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -uppertester_geonetworking_factory uppertester_geonetworking_factory::_f; +#include "uppertester_geonetworking_factory.hh" + +#include "LibItsGeoNetworking_TestSystem.hh" +#include "LibItsGeoNetworking_TypesAndValues.hh" + +#include "loggers.hh" + +uppertester_geonetworking_layer::uppertester_geonetworking_layer(const std::string &p_type, const std::string &p_param) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> uppertester_geonetworking_layer::uppertester_geonetworking_layer: %s, %s", to_string().c_str(), p_param.c_str()); + // Setup parameters + params::convert(_params, p_param); + params::const_iterator it = _params.find(params::loopback); + if (it == _params.cend()) { + _params.insert(std::pair(params::loopback, "0")); + } +} + +void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; + ut_gn_results.utGnInitializeResult() = BOOLEAN(true); + to_all_upper_ports(ut_gn_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(static_cast(send_par), data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; + ut_gn_results.utGnChangePositionResult() = BOOLEAN(true); + to_all_upper_ports(ut_gn_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(static_cast(send_par), data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; + ut_gn_results.utGnTriggerResult() = BOOLEAN(true); + to_all_upper_ports(ut_gn_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_geonetworking_layer::sendMsg(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsGeoNetworking__TypesAndValues::UtGnResults ut_gn_results; + ut_gn_results.utGnTriggerResult() = BOOLEAN(true); + to_all_upper_ports(ut_gn_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_geonetworking_layer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void uppertester_geonetworking_layer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_geonetworking_layer::receive_data: ", data); + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +uppertester_geonetworking_factory uppertester_geonetworking_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.hh index 56b81bc949ffe3f588eb717cb57bbcc11c0feee7..ff2754457222c71b7e9a9155bc951a0b6bd1f46f 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_geonetworking_layer.hh @@ -1,43 +1,43 @@ -/*! - * \file uppertester_geonetworking_layer.hh - * \brief Header file for ITS GeoNetworking protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "t_layer.hh" -#include "uppertester_geonetworking_codec.hh" - -namespace LibItsGeoNetworking__TestSystem { - class UpperTesterPort; -} - -namespace LibItsGeoNetworking__TypesAndValues { - class UtGnInitialize; - class UtGnChangePosition; - class UtGnTrigger; - class UtAutoInteropTrigger; -} // namespace LibItsGeoNetworking__TypesAndValues - -class uppertester_geonetworking_layer : public t_layer { - params _params; - uppertester_geonetworking_codec _codec; - -public: - uppertester_geonetworking_layer() : t_layer(), _params(), _codec(){}; - uppertester_geonetworking_layer(const std::string &p_type, const std::string ¶m); - virtual ~uppertester_geonetworking_layer(){}; - - void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par, params &p_params); - void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par, params &p_params); - void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par, params &p_params); - void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class uppertester_geonetworking_layer +/*! + * \file uppertester_geonetworking_layer.hh + * \brief Header file for ITS GeoNetworking protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "t_layer.hh" +#include "uppertester_geonetworking_codec.hh" + +namespace LibItsGeoNetworking__TestSystem { + class UpperTesterPort; +} + +namespace LibItsGeoNetworking__TypesAndValues { + class UtGnInitialize; + class UtGnChangePosition; + class UtGnTrigger; + class UtAutoInteropTrigger; +} // namespace LibItsGeoNetworking__TypesAndValues + +class uppertester_geonetworking_layer : public t_layer { + params _params; + uppertester_geonetworking_codec _codec; + +public: + uppertester_geonetworking_layer() : t_layer(), _params(), _codec(){}; + uppertester_geonetworking_layer(const std::string &p_type, const std::string ¶m); + virtual ~uppertester_geonetworking_layer(){}; + + void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnInitialize &send_par, params &p_params); + void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnChangePosition &send_par, params &p_params); + void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtGnTrigger &send_par, params &p_params); + void sendMsg(const LibItsGeoNetworking__TypesAndValues::UtAutoInteropTrigger &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class uppertester_geonetworking_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.cc b/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.cc index 8df49b5aa333ea3ac4f1bc35e6cb139b1ed00760..855f91b4334fc977c85151d13e1d625b20d296c5 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.cc @@ -1,278 +1,278 @@ -#include -#include - -#include "loggers.hh" -#include "uppertester_ivim_codec.hh" - -#include "LibItsIvim_TestSystem.hh" -#include "LibItsIvim_TypesAndValues.hh" - -#include "ivim_codec.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char uppertester_ivim_codec::c_utIvimInitialize = 0x00; -unsigned char uppertester_ivim_codec::c_utIvimInitializeResult = 0x01; -unsigned char uppertester_ivim_codec::c_utIvimTrigger = 0x80; -unsigned char uppertester_ivim_codec::c_utIvimTriggerResult = 0x81; -unsigned char uppertester_ivim_codec::c_utIvimUpdate = 0x82; -unsigned char uppertester_ivim_codec::c_utIvimUpdateResult = 0x83; -unsigned char uppertester_ivim_codec::c_utIvimTermination = 0x84; -unsigned char uppertester_ivim_codec::c_utIvimTerminationResult = 0x85; -unsigned char uppertester_ivim_codec::c_utIvimEventIndication = 0x86; - -int uppertester_ivim_codec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_ivim_codec::encode: ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimInitialize") == 0) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimInitialize)); - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimTrigger") == 0) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTrigger)); - // See ETSI TR 103 099 V1.4.1 Clause C.9.1 GenerateIvimEvent - unsigned short flags = 0x0000; - const LibItsIvim__TypesAndValues::UtIvimTrigger &r = static_cast(msg); - if (r.validFrom().is_present()) { // F - flags |= 0x8000; - } - if (r.validTo().is_present()) { // V - flags |= 0x4000; - } - if (r.repetitionInterval().is_present()) { // T - flags |= 0x2000; - } - if (r.zoneIds().is_present()) { // I - flags |= 0x1000; - } - if (r.laneNumber().is_present()) { // L - flags |= 0x0800; - } - if (r.relavanceZoneIds().is_present()) { // Z - flags |= 0x0400; - } - if (r.detectionZoneIds().is_present()) { // D - flags |= 0x0200; - } - if (r.driverAwarenesZoneIds().is_present()) { // A - flags |= 0x0100; - } - if (r.itsRrid().is_present()) { // R - flags |= 0x0080; - } - if (r.directionGic().is_present()) { // G - flags |= 0x0040; - } - if (r.layoutId().is_present()) { // Y - flags |= 0x0020; - } - encoding_buffer.put_c(static_cast((flags >> 8) & 0xFF)); - encoding_buffer.put_c(static_cast(flags & 0x00FF)); - loggers::get_instance().log_to_hexa("uppertester_ivim_codec::encode: flags=", encoding_buffer); - // Continue with encoding - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimUpdate") == 0) { - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimUpdate)); - // See ETSI TR 103 099 V1.4.1 Clause C.9.2 UpdateIvimEvent - unsigned char flags = 0x00; - const LibItsIvim__TypesAndValues::UtIvimUpdate &r = static_cast(msg); - if (r.validFrom().is_present()) { // V - flags |= 0x80; - } - if (r.validTo().is_present()) { // R - flags |= 0x40; - } - if (r.timeStamp().is_present()) { // T - flags |= 0x20; - } - if (r.connectedIviStructures().is_present()) { // C - flags |= 0x10; - } - encoding_buffer.put_c(flags); - loggers::get_instance().log_to_hexa("uppertester_ivim_codec::encode: flags=", encoding_buffer); - // Continue with encoding - } else if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimTermination") == 0) { - // See ETSI TR 103 099 V1.4.1 Clause C.9.3 TerminateIvimEvent - encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTermination)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().log("<<< uppertester_ivim_codec::encode: Return -1"); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< uppertester_ivim_codec::encode: data=", data); - return 0; -} - -int uppertester_ivim_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> uppertester_ivim_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, - dynamic_cast(&type)); - loggers::get_instance().log_msg(">>> uppertester_ivim_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("uppertester_ivim_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("uppertester_ivim_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("uppertester_ivim_codec::encode_: -1 result code returned"); - return -1; - } - } else { - std::string s(r.fld_descr(i)->name); - loggers::get_instance().log("uppertester_ivim_codec::encode_: Padding for %s", field_descriptor.name); - if ((s.rfind(".timeStamp") != string::npos) || (s.rfind(".validFrom") != string::npos) || (s.rfind(".validTo") != string::npos) || - (s.rfind(".repetitionInterval") != string::npos)) { // Pad with six bytes - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - encoding_buffer.put_c((unsigned char)0x00); - } else { // Pad with one bytes - encoding_buffer.put_c((unsigned char)0x00); - } - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - loggers::get_instance().log("uppertester_ivim_codec::encode_: field to process %s", s.c_str()); - if (s.rfind(".iviIdentificationNumber") != string::npos) { - const INTEGER &i = static_cast(type); - loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 2)); - } else if ((s.rfind(".timeStamp") != string::npos) || (s.rfind(".validTo") != string::npos) || (s.rfind(".validFrom") != string::npos) || - (s.rfind(".repetitionInterval") != string::npos)) { - if (type.is_present()) { - const OPTIONAL &o = dynamic_cast &>(type); - const INTEGER & i = static_cast(*o.get_opt_value()); - loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 6)); - } - } else if ((s.rfind(".zoneIds") != string::npos) || (s.rfind(".relavanceZoneId") != string::npos) || (s.rfind(".detectionZoneId") != string::npos) || - (s.rfind(".driverAwarenesZoneId") != string::npos)) { - if (type.is_present()) { - const OPTIONAL &o = dynamic_cast &>(type); - const PreGenRecordOf::PREGEN__RECORD__OF__INTEGER &rov = dynamic_cast(*o.get_opt_value()); - encoding_buffer.put_c(static_cast(rov.lengthof())); - for (int i = 0; i < rov.lengthof(); i++) { - const INTEGER &r = rov[i]; - loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: r=", r); - encoding_buffer.put_string(int2oct(r, 1)); - } // End of 'for' statement - } - } else if (s.rfind(".connectedIviStructures") != string::npos) { - if (type.is_present()) { - const OPTIONAL &o = dynamic_cast &>(type); - const PreGenRecordOf::PREGEN__RECORD__OF__INTEGER &rov = dynamic_cast(*o.get_opt_value()); - encoding_buffer.put_c(static_cast(rov.lengthof())); - for (int i = 0; i < rov.lengthof(); i++) { - const INTEGER &r = rov[i]; - loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: r=", r); - encoding_buffer.put_string(int2oct(r, 4)); - } // End of 'for' statement - } - } else if ((s.rfind(".laneNumber") != string::npos) || (s.rfind(".itsRrid") != string::npos) || (s.rfind(".directionGic") != string::npos) || - (s.rfind(".layoutId") != string::npos)) { - if (type.is_present()) { - const OPTIONAL &o = dynamic_cast &>(type); - const INTEGER & i = static_cast(*o.get_opt_value()); - loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: i=", i); - encoding_buffer.put_string(int2oct(i, 1)); - } - } else { - loggers::get_instance().log("uppertester_ivim_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - } - - loggers::get_instance().log_to_hexa("<<< uppertester_ivim_codec::encode_: encoding_buffer=", encoding_buffer); - return 0; -} - -int uppertester_ivim_codec::decode(const OCTETSTRING &data, Record_Type &msg, params *params) { - TTCN_EncDec::clear_error(); - TTCN_Buffer decoding_buffer(data); - _params = params; - - loggers::get_instance().log_to_hexa(">>> uppertester_ivim_codec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< uppertester_ivim_codec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr uppertester_ivim_codec::decode(const OCTETSTRING &data, params *params) { - - std::unique_ptr result; - - const unsigned char *ptr = static_cast(data); - if (*ptr != uppertester_ivim_codec::c_utIvimEventIndication) { - LibItsIvim__TypesAndValues::UtIvimResults res; - decode(data, res, params); - result.reset((Base_Type *)res.clone()); - } else { - LibItsIvim__TypesAndValues::UtIvimEventInd ind; - decode(data, ind, params); - result.reset((Base_Type *)ind.clone()); - } - - return result; -} - -int uppertester_ivim_codec::decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimResults &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_ivim_codec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == uppertester_ivim_codec::c_utIvimInitializeResult) { - msg.utIvimInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_ivim_codec::c_utIvimTerminationResult) { - msg.utIvimTerminationResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_ivim_codec::c_utIvimTriggerResult) { - LibItsIvim__TypesAndValues::UtIvimTriggerResult r; - ptr += 1; - r.result() = BOOLEAN(*ptr == 0x01); - ptr += 1; - OCTETSTRING os(2, ptr); - ptr += 2; - r.iviIdentificationNumber() = oct2int(os); - msg.utIvimTriggerResult() = r; - } else if (*ptr == uppertester_ivim_codec::c_utIvimUpdateResult) { - LibItsIvim__TypesAndValues::UtIvimUpdateResult r; - ptr += 1; - r.result() = BOOLEAN(*ptr == 0x01); - ptr += 1; - OCTETSTRING os(2, ptr); - ptr += 2; - r.iviIdentificationNumber() = oct2int(os); - msg.utIvimUpdateResult() = r; - } else if (*ptr == uppertester_ivim_codec::c_utIvimTerminationResult) { - ptr += 1; - msg.utIvimTerminationResult() = BOOLEAN(*ptr == 0x01); - } else { - TTCN_warning("uppertester_ivim_codec::decode: Unsupported result"); - } - - loggers::get_instance().log_msg("<<< uppertester_ivim_codec::decode", msg); - return 0; -} - -int uppertester_ivim_codec::decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimEventInd &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_ivim_codec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data) + 1; - OCTETSTRING os(2, ptr); - ptr += 2; - unsigned int length = oct2int(os); - loggers::get_instance().log("uppertester_ivim_codec::decode: IVIM message length=%d", length); - os = OCTETSTRING(length, ptr); - loggers::get_instance().log_to_hexa("uppertester_ivim_codec::decode: IVIM message=", os); - ivim_codec codec; - codec.decode(os, msg.iviMsg(), params); - - loggers::get_instance().log_msg("<<< uppertester_ivim_codec::decode", msg); - return 0; -} +#include +#include + +#include "loggers.hh" +#include "uppertester_ivim_codec.hh" + +#include "LibItsIvim_TestSystem.hh" +#include "LibItsIvim_TypesAndValues.hh" + +#include "ivim_codec.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char uppertester_ivim_codec::c_utIvimInitialize = 0x00; +unsigned char uppertester_ivim_codec::c_utIvimInitializeResult = 0x01; +unsigned char uppertester_ivim_codec::c_utIvimTrigger = 0x80; +unsigned char uppertester_ivim_codec::c_utIvimTriggerResult = 0x81; +unsigned char uppertester_ivim_codec::c_utIvimUpdate = 0x82; +unsigned char uppertester_ivim_codec::c_utIvimUpdateResult = 0x83; +unsigned char uppertester_ivim_codec::c_utIvimTermination = 0x84; +unsigned char uppertester_ivim_codec::c_utIvimTerminationResult = 0x85; +unsigned char uppertester_ivim_codec::c_utIvimEventIndication = 0x86; + +int uppertester_ivim_codec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_ivim_codec::encode: ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimInitialize") == 0) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimInitialize)); + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimTrigger") == 0) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTrigger)); + // See ETSI TR 103 099 V1.4.1 Clause C.9.1 GenerateIvimEvent + unsigned short flags = 0x0000; + const LibItsIvim__TypesAndValues::UtIvimTrigger &r = static_cast(msg); + if (r.validFrom().is_present()) { // F + flags |= 0x8000; + } + if (r.validTo().is_present()) { // V + flags |= 0x4000; + } + if (r.repetitionInterval().is_present()) { // T + flags |= 0x2000; + } + if (r.zoneIds().is_present()) { // I + flags |= 0x1000; + } + if (r.laneNumber().is_present()) { // L + flags |= 0x0800; + } + if (r.relavanceZoneIds().is_present()) { // Z + flags |= 0x0400; + } + if (r.detectionZoneIds().is_present()) { // D + flags |= 0x0200; + } + if (r.driverAwarenesZoneIds().is_present()) { // A + flags |= 0x0100; + } + if (r.itsRrid().is_present()) { // R + flags |= 0x0080; + } + if (r.directionGic().is_present()) { // G + flags |= 0x0040; + } + if (r.layoutId().is_present()) { // Y + flags |= 0x0020; + } + encoding_buffer.put_c(static_cast((flags >> 8) & 0xFF)); + encoding_buffer.put_c(static_cast(flags & 0x00FF)); + loggers::get_instance().log_to_hexa("uppertester_ivim_codec::encode: flags=", encoding_buffer); + // Continue with encoding + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimUpdate") == 0) { + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimUpdate)); + // See ETSI TR 103 099 V1.4.1 Clause C.9.2 UpdateIvimEvent + unsigned char flags = 0x00; + const LibItsIvim__TypesAndValues::UtIvimUpdate &r = static_cast(msg); + if (r.validFrom().is_present()) { // V + flags |= 0x80; + } + if (r.validTo().is_present()) { // R + flags |= 0x40; + } + if (r.timeStamp().is_present()) { // T + flags |= 0x20; + } + if (r.connectedIviStructures().is_present()) { // C + flags |= 0x10; + } + encoding_buffer.put_c(flags); + loggers::get_instance().log_to_hexa("uppertester_ivim_codec::encode: flags=", encoding_buffer); + // Continue with encoding + } else if (std::string(msg.get_descriptor()->name).compare("@LibItsIvim_TypesAndValues.UtIvimTermination") == 0) { + // See ETSI TR 103 099 V1.4.1 Clause C.9.3 TerminateIvimEvent + encoding_buffer.put_c(static_cast(uppertester_ivim_codec::c_utIvimTermination)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().log("<<< uppertester_ivim_codec::encode: Return -1"); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< uppertester_ivim_codec::encode: data=", data); + return 0; +} + +int uppertester_ivim_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> uppertester_ivim_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, + dynamic_cast(&type)); + loggers::get_instance().log_msg(">>> uppertester_ivim_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("uppertester_ivim_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("uppertester_ivim_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("uppertester_ivim_codec::encode_: -1 result code returned"); + return -1; + } + } else { + std::string s(r.fld_descr(i)->name); + loggers::get_instance().log("uppertester_ivim_codec::encode_: Padding for %s", field_descriptor.name); + if ((s.rfind(".timeStamp") != string::npos) || (s.rfind(".validFrom") != string::npos) || (s.rfind(".validTo") != string::npos) || + (s.rfind(".repetitionInterval") != string::npos)) { // Pad with six bytes + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + encoding_buffer.put_c((unsigned char)0x00); + } else { // Pad with one bytes + encoding_buffer.put_c((unsigned char)0x00); + } + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + loggers::get_instance().log("uppertester_ivim_codec::encode_: field to process %s", s.c_str()); + if (s.rfind(".iviIdentificationNumber") != string::npos) { + const INTEGER &i = static_cast(type); + loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 2)); + } else if ((s.rfind(".timeStamp") != string::npos) || (s.rfind(".validTo") != string::npos) || (s.rfind(".validFrom") != string::npos) || + (s.rfind(".repetitionInterval") != string::npos)) { + if (type.is_present()) { + const OPTIONAL &o = dynamic_cast &>(type); + const INTEGER & i = static_cast(*o.get_opt_value()); + loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 6)); + } + } else if ((s.rfind(".zoneIds") != string::npos) || (s.rfind(".relavanceZoneId") != string::npos) || (s.rfind(".detectionZoneId") != string::npos) || + (s.rfind(".driverAwarenesZoneId") != string::npos)) { + if (type.is_present()) { + const OPTIONAL &o = dynamic_cast &>(type); + const PreGenRecordOf::PREGEN__RECORD__OF__INTEGER &rov = dynamic_cast(*o.get_opt_value()); + encoding_buffer.put_c(static_cast(rov.lengthof())); + for (int i = 0; i < rov.lengthof(); i++) { + const INTEGER &r = rov[i]; + loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: r=", r); + encoding_buffer.put_string(int2oct(r, 1)); + } // End of 'for' statement + } + } else if (s.rfind(".connectedIviStructures") != string::npos) { + if (type.is_present()) { + const OPTIONAL &o = dynamic_cast &>(type); + const PreGenRecordOf::PREGEN__RECORD__OF__INTEGER &rov = dynamic_cast(*o.get_opt_value()); + encoding_buffer.put_c(static_cast(rov.lengthof())); + for (int i = 0; i < rov.lengthof(); i++) { + const INTEGER &r = rov[i]; + loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: r=", r); + encoding_buffer.put_string(int2oct(r, 4)); + } // End of 'for' statement + } + } else if ((s.rfind(".laneNumber") != string::npos) || (s.rfind(".itsRrid") != string::npos) || (s.rfind(".directionGic") != string::npos) || + (s.rfind(".layoutId") != string::npos)) { + if (type.is_present()) { + const OPTIONAL &o = dynamic_cast &>(type); + const INTEGER & i = static_cast(*o.get_opt_value()); + loggers::get_instance().log_msg("uppertester_ivim_codec::encode_: i=", i); + encoding_buffer.put_string(int2oct(i, 1)); + } + } else { + loggers::get_instance().log("uppertester_ivim_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + } + + loggers::get_instance().log_to_hexa("<<< uppertester_ivim_codec::encode_: encoding_buffer=", encoding_buffer); + return 0; +} + +int uppertester_ivim_codec::decode(const OCTETSTRING &data, Record_Type &msg, params *params) { + TTCN_EncDec::clear_error(); + TTCN_Buffer decoding_buffer(data); + _params = params; + + loggers::get_instance().log_to_hexa(">>> uppertester_ivim_codec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< uppertester_ivim_codec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr uppertester_ivim_codec::decode(const OCTETSTRING &data, params *params) { + + std::unique_ptr result; + + const unsigned char *ptr = static_cast(data); + if (*ptr != uppertester_ivim_codec::c_utIvimEventIndication) { + LibItsIvim__TypesAndValues::UtIvimResults res; + decode(data, res, params); + result.reset((Base_Type *)res.clone()); + } else { + LibItsIvim__TypesAndValues::UtIvimEventInd ind; + decode(data, ind, params); + result.reset((Base_Type *)ind.clone()); + } + + return result; +} + +int uppertester_ivim_codec::decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimResults &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_ivim_codec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == uppertester_ivim_codec::c_utIvimInitializeResult) { + msg.utIvimInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_ivim_codec::c_utIvimTerminationResult) { + msg.utIvimTerminationResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_ivim_codec::c_utIvimTriggerResult) { + LibItsIvim__TypesAndValues::UtIvimTriggerResult r; + ptr += 1; + r.result() = BOOLEAN(*ptr == 0x01); + ptr += 1; + OCTETSTRING os(2, ptr); + ptr += 2; + r.iviIdentificationNumber() = oct2int(os); + msg.utIvimTriggerResult() = r; + } else if (*ptr == uppertester_ivim_codec::c_utIvimUpdateResult) { + LibItsIvim__TypesAndValues::UtIvimUpdateResult r; + ptr += 1; + r.result() = BOOLEAN(*ptr == 0x01); + ptr += 1; + OCTETSTRING os(2, ptr); + ptr += 2; + r.iviIdentificationNumber() = oct2int(os); + msg.utIvimUpdateResult() = r; + } else if (*ptr == uppertester_ivim_codec::c_utIvimTerminationResult) { + ptr += 1; + msg.utIvimTerminationResult() = BOOLEAN(*ptr == 0x01); + } else { + TTCN_warning("uppertester_ivim_codec::decode: Unsupported result"); + } + + loggers::get_instance().log_msg("<<< uppertester_ivim_codec::decode", msg); + return 0; +} + +int uppertester_ivim_codec::decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimEventInd &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_ivim_codec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data) + 1; + OCTETSTRING os(2, ptr); + ptr += 2; + unsigned int length = oct2int(os); + loggers::get_instance().log("uppertester_ivim_codec::decode: IVIM message length=%d", length); + os = OCTETSTRING(length, ptr); + loggers::get_instance().log_to_hexa("uppertester_ivim_codec::decode: IVIM message=", os); + ivim_codec codec; + codec.decode(os, msg.iviMsg(), params); + + loggers::get_instance().log_msg("<<< uppertester_ivim_codec::decode", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.hh b/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.hh index f08e0e19d6be68a9aa18846fa44b6266cf2232c4..76d579cd2a0815f86a9a74911a7db936453273a3 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_ivim_codec.hh @@ -1,53 +1,53 @@ -/*! - * \file uppertester_denm_codec.hh - * \brief Header file for ITS UpperTester IVIM codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsIvim__TypesAndValues { - class UtIvimResults; - class UtIvimEventInd; -} // namespace LibItsIvim__TypesAndValues - -class uppertester_ivim_codec : public codec { -public: - static unsigned char c_utIvimInitialize; - static unsigned char c_utIvimInitializeResult; - static unsigned char c_utIvimTrigger; - static unsigned char c_utIvimTriggerResult; - static unsigned char c_utIvimUpdate; - static unsigned char c_utIvimUpdateResult; - static unsigned char c_utIvimTermination; - static unsigned char c_utIvimTerminationResult; - static unsigned char c_utIvimEventIndication; - - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - uppertester_ivim_codec() : codec(){}; - virtual ~uppertester_ivim_codec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimEventInd &msg, params *params = NULL); -}; // End of class uppertester_ivim_codec +/*! + * \file uppertester_denm_codec.hh + * \brief Header file for ITS UpperTester IVIM codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsIvim__TypesAndValues { + class UtIvimResults; + class UtIvimEventInd; +} // namespace LibItsIvim__TypesAndValues + +class uppertester_ivim_codec : public codec { +public: + static unsigned char c_utIvimInitialize; + static unsigned char c_utIvimInitializeResult; + static unsigned char c_utIvimTrigger; + static unsigned char c_utIvimTriggerResult; + static unsigned char c_utIvimUpdate; + static unsigned char c_utIvimUpdateResult; + static unsigned char c_utIvimTermination; + static unsigned char c_utIvimTerminationResult; + static unsigned char c_utIvimEventIndication; + + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + uppertester_ivim_codec() : codec(){}; + virtual ~uppertester_ivim_codec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsIvim__TypesAndValues::UtIvimEventInd &msg, params *params = NULL); +}; // End of class uppertester_ivim_codec diff --git a/ccsrc/Protocols/UpperTester/uppertester_ivim_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_ivim_factory.hh index 063f4f7b2ee6ad387582f0eeb15a4f6ff4ed219b..fbbd9e820bc8b69a5c78f7202506f60baf49e971 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_ivim_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_ivim_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file uppertester_ivim_factory.hh - * \brief Header file for ITS IVIM Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_ivim_layer.hh" - -class uppertester_ivim_factory : public layer_factory { - static uppertester_ivim_factory _f; - -public: - uppertester_ivim_factory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_IVIM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_ivim_layer(p_type, p_param); }; -}; // End of class uppertester_ivim_factory +/*! + * \file uppertester_ivim_factory.hh + * \brief Header file for ITS IVIM Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_ivim_layer.hh" + +class uppertester_ivim_factory : public layer_factory { + static uppertester_ivim_factory _f; + +public: + uppertester_ivim_factory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_IVIM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_ivim_layer(p_type, p_param); }; +}; // End of class uppertester_ivim_factory diff --git a/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.cc index 611a195e6a1f1712fe4cf22634156b8452d39e96..d5d7a39b3ae86f3a35197253eb5d78113e3e150b 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.cc @@ -1,71 +1,71 @@ -#include "uppertester_ivim_factory.hh" - -#include "LibItsIvim_TestSystem.hh" -#include "LibItsIvim_TypesAndValues.hh" - -#include "loggers.hh" - -uppertester_ivim_layer::uppertester_ivim_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> uppertester_ivim_layer::uppertester_ivim_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); -} - -void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); -} - -void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); -} - -void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void uppertester_ivim_layer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_ivim_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void uppertester_ivim_layer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_ivim_layer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -uppertester_ivim_factory uppertester_ivim_factory::_f; +#include "uppertester_ivim_factory.hh" + +#include "LibItsIvim_TestSystem.hh" +#include "LibItsIvim_TypesAndValues.hh" + +#include "loggers.hh" + +uppertester_ivim_layer::uppertester_ivim_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> uppertester_ivim_layer::uppertester_ivim_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); +} + +void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); +} + +void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); +} + +void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void uppertester_ivim_layer::sendMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_ivim_layer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void uppertester_ivim_layer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_ivim_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void uppertester_ivim_layer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_ivim_layer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +uppertester_ivim_factory uppertester_ivim_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.hh index 3ea1aa5735a56483c0975b2081cb0ab2b835edf0..8642d1024c89be7e83d286335307d4464b596cd2 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_ivim_layer.hh @@ -1,43 +1,43 @@ -/*! - * \file uppertester_ivim_layer.hh - * \brief Header file for ITS UpperTester IVIM protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "t_layer.hh" -#include "uppertester_ivim_codec.hh" - -namespace LibItsIvim__TestSystem { - class UpperTesterPort; -} - -namespace LibItsIvim__TypesAndValues { - class UtIvimInitialize; - class UtIvimTrigger; - class UtIvimUpdate; - class UtIvimTermination; -} // namespace LibItsIvim__TypesAndValues - -class uppertester_ivim_layer : public t_layer { - params _params; - uppertester_ivim_codec _codec; - -public: - uppertester_ivim_layer() : t_layer(), _params(), _codec(){}; - uppertester_ivim_layer(const std::string &p_type, const std::string ¶m); - virtual ~uppertester_ivim_layer(){}; - - void sendMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par, params &p_params); - void sendMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par, params &p_params); - void sendMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par, params &p_params); - void sendMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class uppertester_ivim_layer +/*! + * \file uppertester_ivim_layer.hh + * \brief Header file for ITS UpperTester IVIM protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "t_layer.hh" +#include "uppertester_ivim_codec.hh" + +namespace LibItsIvim__TestSystem { + class UpperTesterPort; +} + +namespace LibItsIvim__TypesAndValues { + class UtIvimInitialize; + class UtIvimTrigger; + class UtIvimUpdate; + class UtIvimTermination; +} // namespace LibItsIvim__TypesAndValues + +class uppertester_ivim_layer : public t_layer { + params _params; + uppertester_ivim_codec _codec; + +public: + uppertester_ivim_layer() : t_layer(), _params(), _codec(){}; + uppertester_ivim_layer(const std::string &p_type, const std::string ¶m); + virtual ~uppertester_ivim_layer(){}; + + void sendMsg(const LibItsIvim__TypesAndValues::UtIvimInitialize &send_par, params &p_params); + void sendMsg(const LibItsIvim__TypesAndValues::UtIvimTrigger &send_par, params &p_params); + void sendMsg(const LibItsIvim__TypesAndValues::UtIvimUpdate &send_par, params &p_params); + void sendMsg(const LibItsIvim__TypesAndValues::UtIvimTermination &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class uppertester_ivim_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.cc b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.cc index 4512524b32f661d92e5350d94f364494eced1534..ea406774b761329d9fbf406ae7caf6930acd4e94 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.cc @@ -94,9 +94,9 @@ int uppertester_mapem_spatem_codec::encode_(const Base_Type &type, const TTCN_Ty } } else if (s.rfind(".regulatorySpeedLimit") == 0) { if (type.is_present()) { - const OPTIONAL &o = - dynamic_cast &>(type); - const DSRC__REGION__noCircular::RegulatorySpeedLimit &rv = dynamic_cast(*o.get_opt_value()); + const OPTIONAL &o = + dynamic_cast &>(type); + const DSRC__noCircular::RegulatorySpeedLimit &rv = dynamic_cast(*o.get_opt_value()); const int t = rv.type__().as_int(); encoding_buffer.put_c((unsigned char)t); const int s = rv.speed(); diff --git a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.hh b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.hh index 1487d77da17240f0db6d7ddf55333f769a0ec184..99d275af2383e0e21c6382e86c11c78f22f58a53 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_codec.hh @@ -1,52 +1,52 @@ -/*! - * \file uppertester_mapem_spatem_codec.hh - * \brief Header file for ITS UpperTester MAPEM/SPATEM codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsMapemSpatem__TypesAndValues { - class UtMapemSpatemResults; - class UtMapemEventInd; - class UtSpatemEventInd; -} // namespace LibItsMapemSpatem__TypesAndValues - -class uppertester_mapem_spatem_codec : public codec { -public: - static unsigned char c_utMapemSpatemInitialize; - static unsigned char c_utMapemSpatemInitializeResult; - static unsigned char c_utMapemSpatemTrigger; - static unsigned char c_utMapemSpatemTriggerResult; - static unsigned char c_utMapemEventIndication; - static unsigned char c_utSpatemEventIndication; - - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - uppertester_mapem_spatem_codec() : codec(){}; - virtual ~uppertester_mapem_spatem_codec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &msg, params *params = NULL); - int decode(const OCTETSTRING &data, LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &msg, params *params = NULL); -}; // End of class uppertester_mapem_spatem_codec +/*! + * \file uppertester_mapem_spatem_codec.hh + * \brief Header file for ITS UpperTester MAPEM/SPATEM codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsMapemSpatem__TypesAndValues { + class UtMapemSpatemResults; + class UtMapemEventInd; + class UtSpatemEventInd; +} // namespace LibItsMapemSpatem__TypesAndValues + +class uppertester_mapem_spatem_codec : public codec { +public: + static unsigned char c_utMapemSpatemInitialize; + static unsigned char c_utMapemSpatemInitializeResult; + static unsigned char c_utMapemSpatemTrigger; + static unsigned char c_utMapemSpatemTriggerResult; + static unsigned char c_utMapemEventIndication; + static unsigned char c_utSpatemEventIndication; + + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + uppertester_mapem_spatem_codec() : codec(){}; + virtual ~uppertester_mapem_spatem_codec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsMapemSpatem__TypesAndValues::UtMapemSpatemResults &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsMapemSpatem__TypesAndValues::UtMapemEventInd &msg, params *params = NULL); + int decode(const OCTETSTRING &data, LibItsMapemSpatem__TypesAndValues::UtSpatemEventInd &msg, params *params = NULL); +}; // End of class uppertester_mapem_spatem_codec diff --git a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_factory.hh index e0d4040f827600a07ad2cc0876694b27209d4f5b..8f1209f83cfe93164f0bf0662354cd3337dc0465 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file uppertester_mapem_spatem_factory.hh - * \brief Header file for ITS MAPEM/SPATEM Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_mapem_spatem_layer.hh" - -class uppertester_mapem_spatem_factory : public layer_factory { - static uppertester_mapem_spatem_factory _f; - -public: - uppertester_mapem_spatem_factory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_MAPEMSPATEM", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_mapem_spatem_layer(p_type, p_param); }; -}; // End of class uppertester_mapem_spatem_factory +/*! + * \file uppertester_mapem_spatem_factory.hh + * \brief Header file for ITS MAPEM/SPATEM Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_mapem_spatem_layer.hh" + +class uppertester_mapem_spatem_factory : public layer_factory { + static uppertester_mapem_spatem_factory _f; + +public: + uppertester_mapem_spatem_factory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_MAPEMSPATEM", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_mapem_spatem_layer(p_type, p_param); }; +}; // End of class uppertester_mapem_spatem_factory diff --git a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.cc index 1a04797e18b08d0b600f04895bc9690c742faf5b..3d41426b2a9cc9f51dbb9762ad4c0530c4ee33e9 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.cc @@ -1,51 +1,51 @@ -#include "uppertester_mapem_spatem_factory.hh" - -#include "LibItsMapemSpatem_TestSystem.hh" -#include "LibItsMapemSpatem_TypesAndValues.hh" - -#include "loggers.hh" - -uppertester_mapem_spatem_layer::uppertester_mapem_spatem_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> uppertester_mapem_spatem_layer::uppertester_mapem_spatem_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); -} - -void uppertester_mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); -} - -void uppertester_mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::sendMsg", send_par); - - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); -} - -void uppertester_mapem_spatem_layer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void uppertester_mapem_spatem_layer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -uppertester_mapem_spatem_factory uppertester_mapem_spatem_factory::_f; +#include "uppertester_mapem_spatem_factory.hh" + +#include "LibItsMapemSpatem_TestSystem.hh" +#include "LibItsMapemSpatem_TypesAndValues.hh" + +#include "loggers.hh" + +uppertester_mapem_spatem_layer::uppertester_mapem_spatem_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> uppertester_mapem_spatem_layer::uppertester_mapem_spatem_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); +} + +void uppertester_mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); +} + +void uppertester_mapem_spatem_layer::sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::sendMsg", send_par); + + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); +} + +void uppertester_mapem_spatem_layer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void uppertester_mapem_spatem_layer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_mapem_spatem_layer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +uppertester_mapem_spatem_factory uppertester_mapem_spatem_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.hh index 4b1b5f3f391d8721117c6dc0f0a24fc794e2b36b..e2b0cc786980a13926ae0a86c1dd9c2c3dcffb12 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_mapem_spatem_layer.hh @@ -1,40 +1,40 @@ -/*! - * \file uppertester_mapem_spatem_layer.hh - * \brief Header file for ITS MapemSpatem protocol layer. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "t_layer.hh" -#include "uppertester_mapem_spatem_codec.hh" - -namespace LibItsMapemSpatem__TestSystem { - class UpperTesterPort; -} - -namespace LibItsMapemSpatem__TypesAndValues { - class UtMapemSpatemInitialize; - class UtMapemSpatemChangePosition; - class UtMapemSpatemTrigger; -} // namespace LibItsMapemSpatem__TypesAndValues - -class uppertester_mapem_spatem_layer : public t_layer { - params _params; - uppertester_mapem_spatem_codec _codec; - -public: - uppertester_mapem_spatem_layer() : t_layer(), _params(), _codec(){}; - uppertester_mapem_spatem_layer(const std::string &p_type, const std::string ¶m); - virtual ~uppertester_mapem_spatem_layer(){}; - - void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par, params &p_params); - void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class uppertester_mapem_spatem_layer +/*! + * \file uppertester_mapem_spatem_layer.hh + * \brief Header file for ITS MapemSpatem protocol layer. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "t_layer.hh" +#include "uppertester_mapem_spatem_codec.hh" + +namespace LibItsMapemSpatem__TestSystem { + class UpperTesterPort; +} + +namespace LibItsMapemSpatem__TypesAndValues { + class UtMapemSpatemInitialize; + class UtMapemSpatemChangePosition; + class UtMapemSpatemTrigger; +} // namespace LibItsMapemSpatem__TypesAndValues + +class uppertester_mapem_spatem_layer : public t_layer { + params _params; + uppertester_mapem_spatem_codec _codec; + +public: + uppertester_mapem_spatem_layer() : t_layer(), _params(), _codec(){}; + uppertester_mapem_spatem_layer(const std::string &p_type, const std::string ¶m); + virtual ~uppertester_mapem_spatem_layer(){}; + + void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemInitialize &send_par, params &p_params); + void sendMsg(const LibItsMapemSpatem__TypesAndValues::UtMapemSpatemTrigger &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class uppertester_mapem_spatem_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_pki_codec.cc b/ccsrc/Protocols/UpperTester/uppertester_pki_codec.cc index 938c0ead32fc1d464cda5e8cd887b4867ea3a5d2..b017157495f20e0ba16ff4f2847bbe7c9e569b7b 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_pki_codec.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_pki_codec.cc @@ -1,143 +1,143 @@ -#include -//#include - -#include "loggers.hh" -#include "uppertester_pki_codec.hh" - -#include "LibItsPki_TestSystem.hh" -#include "LibItsPki_TypesAndValues.hh" - -//#include "pki_codec.hh" - -template class OPTIONAL; -class TTCN_EncDec; - -unsigned char uppertester_pki_codec::c_utPkiInitialize = 0x00; -unsigned char uppertester_pki_codec::c_utPkiInitializeResult = 0x01; -unsigned char uppertester_pki_codec::c_utPkiTriggerResult = 0xD2; -unsigned char uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest = 0xD0; -unsigned char uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest = 0xD1; - -int uppertester_pki_codec::encode(const Record_Type &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_pki_codec::encode (1): ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - if (std::string(msg.get_descriptor()->name).compare("@LibItsPki_TypesAndValues.UtPkiInitialize") == 0) { - encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiInitialize)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().warning("<<< uppertester_pki_codec::encode: Failed to encode UT message"); - return -1; - } - encode_(msg, *msg.get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< uppertester_pki_codec::encode: data=", data); - return 0; -} - -int uppertester_pki_codec::encode(const LibItsPki__TypesAndValues::UtPkiTrigger &msg, OCTETSTRING &data) { - loggers::get_instance().log_msg(">>> uppertester_pki_codec::encode (2): ", (const Record_Type &)msg); - - TTCN_EncDec::clear_error(); - TTCN_Buffer encoding_buffer; - // const Record_Type *type; - const LibItsPki__TypesAndValues::UtPkiTrigger &u = static_cast(msg); - if (u.ischosen(LibItsPki__TypesAndValues::UtPkiTrigger::ALT_triggerEnrolmentRequest)) { - encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest)); - /*encoding_buffer.put_c(static_cast(u.triggerEnrolmentRequest().cannonicalId().lengthof())); // Length of the string - encoding_buffer.put_string(u.triggerEnrolmentRequest().cannonicalId()); - encoding_buffer.put_os(u.triggerEnrolmentRequest().encAlgorithm()); // One byte - encoding_buffer.put_os(u.triggerEnrolmentRequest().privateKey()); // 32 bytes - encoding_buffer.put_os(u.triggerEnrolmentRequest().compressedPublickey()); //33 bytes - */ - } else if (u.ischosen(LibItsPki__TypesAndValues::UtPkiTrigger::ALT_triggerAuthorizationRequest)) { - encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest)); - } else { // Error - data = OCTETSTRING(0, nullptr); - loggers::get_instance().warning("<<< uppertester_pki_codec::encode: Failed to encode UT message"); - return -1; - } - // encode_(*type, *type->get_descriptor(), encoding_buffer); - data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); - loggers::get_instance().log_msg("<<< uppertester_pki_codec::encode: data=", data); - return 0; -} - -int uppertester_pki_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { - loggers::get_instance().log(">>> uppertester_pki_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, - dynamic_cast(&type)); - loggers::get_instance().log_msg(">>> uppertester_pki_codec::encode_: ", type); - - if (dynamic_cast(&type) != NULL) { - const Record_Type &r = (const Record_Type &)type; - loggers::get_instance().log("uppertester_pki_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); - for (int i = 0; i < r.get_count(); i++) { - loggers::get_instance().log("uppertester_pki_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), - r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); - if (r.get_at(i)->is_present()) { - if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { - loggers::get_instance().warning("uppertester_pki_codec::encode_: -1 result code returned"); - return -1; - } - } else if (std::string(r.fld_name(i)).compare("alacarte") == 0) { - // Add empty field length - loggers::get_instance().log("uppertester_pki_codec::encode_: alacarte is missing, add 0x00"); - encoding_buffer.put_c(0x00); - } - } // End of 'for' statement - } else { - std::string s(field_descriptor.name); - loggers::get_instance().log("uppertester_pki_codec::encode_: field to process %s", s.c_str()); - - loggers::get_instance().log("uppertester_pki_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); - type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); - } - - loggers::get_instance().log_to_hexa("<<>> uppertester_pki_codec::decode: decoding_buffer=", decoding_buffer); - // decode_(msg, *msg.get_descriptor(), decoding_buffer); - - loggers::get_instance().log_msg("<<< uppertester_pki_codec::decode: ", (const Record_Type &)msg); - return 0; -} - -std::unique_ptr uppertester_pki_codec::decode(const OCTETSTRING &data, params *params) { - - std::unique_ptr result; - - const unsigned char * ptr = static_cast(data); - LibItsPki__TypesAndValues::UtPkiResults res; - if (decode(data, res, params) == 0) { - result.reset((Base_Type *)res.clone()); - } else { - result.reset(nullptr); - } - - return result; -} - -int uppertester_pki_codec::decode(const OCTETSTRING &data, LibItsPki__TypesAndValues::UtPkiResults &msg, params *params) { - loggers::get_instance().log_to_hexa(">>> uppertester_pki_codec::decode: decoding_buffer=", data); - - const unsigned char *ptr = static_cast(data); - if (*ptr == uppertester_pki_codec::c_utPkiInitializeResult) { - msg.utPkiInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else if (*ptr == uppertester_pki_codec::c_utPkiTriggerResult) { - msg.utPkiTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); - } else { - loggers::get_instance().warning("uppertester_pki_codec::decode: Unsupported result"); - return -1; - } - - loggers::get_instance().log_msg("<<< uppertester_pki_codec::decode", msg); - return 0; -} +#include +//#include + +#include "loggers.hh" +#include "uppertester_pki_codec.hh" + +#include "LibItsPki_TestSystem.hh" +#include "LibItsPki_TypesAndValues.hh" + +//#include "pki_codec.hh" + +template class OPTIONAL; +class TTCN_EncDec; + +unsigned char uppertester_pki_codec::c_utPkiInitialize = 0x00; +unsigned char uppertester_pki_codec::c_utPkiInitializeResult = 0x01; +unsigned char uppertester_pki_codec::c_utPkiTriggerResult = 0xD2; +unsigned char uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest = 0xD0; +unsigned char uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest = 0xD1; + +int uppertester_pki_codec::encode(const Record_Type &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_pki_codec::encode (1): ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + if (std::string(msg.get_descriptor()->name).compare("@LibItsPki_TypesAndValues.UtPkiInitialize") == 0) { + encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiInitialize)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().warning("<<< uppertester_pki_codec::encode: Failed to encode UT message"); + return -1; + } + encode_(msg, *msg.get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< uppertester_pki_codec::encode: data=", data); + return 0; +} + +int uppertester_pki_codec::encode(const LibItsPki__TypesAndValues::UtPkiTrigger &msg, OCTETSTRING &data) { + loggers::get_instance().log_msg(">>> uppertester_pki_codec::encode (2): ", (const Record_Type &)msg); + + TTCN_EncDec::clear_error(); + TTCN_Buffer encoding_buffer; + // const Record_Type *type; + const LibItsPki__TypesAndValues::UtPkiTrigger &u = static_cast(msg); + if (u.ischosen(LibItsPki__TypesAndValues::UtPkiTrigger::ALT_triggerEnrolmentRequest)) { + encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiTriggerEnrolmentRequest)); + /*encoding_buffer.put_c(static_cast(u.triggerEnrolmentRequest().cannonicalId().lengthof())); // Length of the string + encoding_buffer.put_string(u.triggerEnrolmentRequest().cannonicalId()); + encoding_buffer.put_os(u.triggerEnrolmentRequest().encAlgorithm()); // One byte + encoding_buffer.put_os(u.triggerEnrolmentRequest().privateKey()); // 32 bytes + encoding_buffer.put_os(u.triggerEnrolmentRequest().compressedPublickey()); //33 bytes + */ + } else if (u.ischosen(LibItsPki__TypesAndValues::UtPkiTrigger::ALT_triggerAuthorizationRequest)) { + encoding_buffer.put_c(static_cast(uppertester_pki_codec::c_utPkiTriggerAuthorizationRequest)); + } else { // Error + data = OCTETSTRING(0, nullptr); + loggers::get_instance().warning("<<< uppertester_pki_codec::encode: Failed to encode UT message"); + return -1; + } + // encode_(*type, *type->get_descriptor(), encoding_buffer); + data = OCTETSTRING(encoding_buffer.get_len(), encoding_buffer.get_data()); + loggers::get_instance().log_msg("<<< uppertester_pki_codec::encode: data=", data); + return 0; +} + +int uppertester_pki_codec::encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer) { + loggers::get_instance().log(">>> uppertester_pki_codec::encode_: processing %s/%s/%p", type.get_descriptor()->name, field_descriptor.name, + dynamic_cast(&type)); + loggers::get_instance().log_msg(">>> uppertester_pki_codec::encode_: ", type); + + if (dynamic_cast(&type) != NULL) { + const Record_Type &r = (const Record_Type &)type; + loggers::get_instance().log("uppertester_pki_codec::encode_: processing Record_Type %s", r.get_descriptor()->name); + for (int i = 0; i < r.get_count(); i++) { + loggers::get_instance().log("uppertester_pki_codec::encode_: processing %s/%s/%s - %d (1 ==> use dynamic_cast) - %d", r.fld_name(i), + r.fld_descr(i)->name, r.get_at(i)->get_descriptor()->name, r.get_at(i)->is_optional(), r.get_at(i)->is_present()); + if (r.get_at(i)->is_present()) { + if (encode_(*r.get_at(i), *r.fld_descr(i), encoding_buffer) == -1) { + loggers::get_instance().warning("uppertester_pki_codec::encode_: -1 result code returned"); + return -1; + } + } else if (std::string(r.fld_name(i)).compare("alacarte") == 0) { + // Add empty field length + loggers::get_instance().log("uppertester_pki_codec::encode_: alacarte is missing, add 0x00"); + encoding_buffer.put_c(0x00); + } + } // End of 'for' statement + } else { + std::string s(field_descriptor.name); + loggers::get_instance().log("uppertester_pki_codec::encode_: field to process %s", s.c_str()); + + loggers::get_instance().log("uppertester_pki_codec::encode_ (else): processing type %s/%s", type.get_descriptor()->name, field_descriptor.name); + type.encode(field_descriptor, encoding_buffer, TTCN_EncDec::CT_RAW); + } + + loggers::get_instance().log_to_hexa("<<>> uppertester_pki_codec::decode: decoding_buffer=", decoding_buffer); + // decode_(msg, *msg.get_descriptor(), decoding_buffer); + + loggers::get_instance().log_msg("<<< uppertester_pki_codec::decode: ", (const Record_Type &)msg); + return 0; +} + +std::unique_ptr uppertester_pki_codec::decode(const OCTETSTRING &data, params *params) { + + std::unique_ptr result; + + const unsigned char * ptr = static_cast(data); + LibItsPki__TypesAndValues::UtPkiResults res; + if (decode(data, res, params) == 0) { + result.reset((Base_Type *)res.clone()); + } else { + result.reset(nullptr); + } + + return result; +} + +int uppertester_pki_codec::decode(const OCTETSTRING &data, LibItsPki__TypesAndValues::UtPkiResults &msg, params *params) { + loggers::get_instance().log_to_hexa(">>> uppertester_pki_codec::decode: decoding_buffer=", data); + + const unsigned char *ptr = static_cast(data); + if (*ptr == uppertester_pki_codec::c_utPkiInitializeResult) { + msg.utPkiInitializeResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else if (*ptr == uppertester_pki_codec::c_utPkiTriggerResult) { + msg.utPkiTriggerResult() = BOOLEAN(*(ptr + 1) == 0x01); + } else { + loggers::get_instance().warning("uppertester_pki_codec::decode: Unsupported result"); + return -1; + } + + loggers::get_instance().log_msg("<<< uppertester_pki_codec::decode", msg); + return 0; +} diff --git a/ccsrc/Protocols/UpperTester/uppertester_pki_codec.hh b/ccsrc/Protocols/UpperTester/uppertester_pki_codec.hh index 5cf009e229b684ed36b8f6b8c38426378d9c767f..086fef85b24a240ff08f2e4dc7737d924be86f55 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_pki_codec.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_pki_codec.hh @@ -1,51 +1,51 @@ -/*! - * \file uppertester_pki_codec.hh - * \brief Header file for ITS UpperTester PKI codec definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "codec.hh" -#include "params.hh" - -class Base_Type; -class Record_Type; -class TTCN_Typedescriptor_t; -class TTCN_Buffer; - -namespace LibItsPki__TypesAndValues { - class UtPkiTrigger; - class UtPkiResults; - class UtPkiEventInd; -} // namespace LibItsPki__TypesAndValues - -class uppertester_pki_codec : public codec { -public: - static unsigned char c_utPkiInitialize; - static unsigned char c_utPkiInitializeResult; - static unsigned char c_utPkiTriggerResult; - static unsigned char c_utPkiTriggerEnrolmentRequest; - static unsigned char c_utPkiTriggerAuthorizationRequest; - -private: - int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); - -public: - uppertester_pki_codec() : codec(){}; - virtual ~uppertester_pki_codec(){}; - - virtual int encode(const Record_Type &, OCTETSTRING &data); - int encode(const LibItsPki__TypesAndValues::UtPkiTrigger &, OCTETSTRING &data); - virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); - std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); - -private: - int decode(const OCTETSTRING &data, LibItsPki__TypesAndValues::UtPkiResults &msg, params *params = NULL); -}; // End of class uppertester_pki_codec +/*! + * \file uppertester_pki_codec.hh + * \brief Header file for ITS UpperTester PKI codec definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "codec.hh" +#include "params.hh" + +class Base_Type; +class Record_Type; +class TTCN_Typedescriptor_t; +class TTCN_Buffer; + +namespace LibItsPki__TypesAndValues { + class UtPkiTrigger; + class UtPkiResults; + class UtPkiEventInd; +} // namespace LibItsPki__TypesAndValues + +class uppertester_pki_codec : public codec { +public: + static unsigned char c_utPkiInitialize; + static unsigned char c_utPkiInitializeResult; + static unsigned char c_utPkiTriggerResult; + static unsigned char c_utPkiTriggerEnrolmentRequest; + static unsigned char c_utPkiTriggerAuthorizationRequest; + +private: + int encode_(const Base_Type &type, const TTCN_Typedescriptor_t &field_descriptor, TTCN_Buffer &encoding_buffer); + +public: + uppertester_pki_codec() : codec(){}; + virtual ~uppertester_pki_codec(){}; + + virtual int encode(const Record_Type &, OCTETSTRING &data); + int encode(const LibItsPki__TypesAndValues::UtPkiTrigger &, OCTETSTRING &data); + virtual int decode(const OCTETSTRING &data, Record_Type &, params *params = NULL); + std::unique_ptr decode(const OCTETSTRING &data, params *params = NULL); + +private: + int decode(const OCTETSTRING &data, LibItsPki__TypesAndValues::UtPkiResults &msg, params *params = NULL); +}; // End of class uppertester_pki_codec diff --git a/ccsrc/Protocols/UpperTester/uppertester_pki_layer.cc b/ccsrc/Protocols/UpperTester/uppertester_pki_layer.cc index f967c82dd30c03f2870953059b0258d68b93c927..b23ae0389e5fc4600dcb2807faed2d26bfff9608 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_pki_layer.cc +++ b/ccsrc/Protocols/UpperTester/uppertester_pki_layer.cc @@ -1,67 +1,67 @@ -#include "uppertester_pki_layer_factory.hh" - -#include "LibItsPki_TestSystem.hh" -#include "LibItsPki_TypesAndValues.hh" - -#include "loggers.hh" - -uppertester_pki_layer::uppertester_pki_layer(const std::string &p_type, const std::string ¶m) - : t_layer(p_type), _params(), _codec() { - loggers::get_instance().log(">>> uppertester_pki_layer::uppertester_pki_layer: %s, %s", to_string().c_str(), param.c_str()); - // Setup parameters - params::convert(_params, param); - params::const_iterator it = _params.find(params::loopback); - if (it == _params.cend()) { - _params.insert(std::pair(params::loopback, "0")); - } -} - -void uppertester_pki_layer::sendMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_pki_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsPki__TypesAndValues::UtPkiResults ut_pki_results; - ut_pki_results.utPkiInitializeResult() = BOOLEAN(true); - to_all_upper_ports(ut_pki_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode((const Record_Type &)send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_pki_layer::sendMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_pki_layer::sendMsg", send_par); - - if (_params[params::loopback].compare("1") == 0) { - LibItsPki__TypesAndValues::UtPkiResults ut_pki_results; - ut_pki_results.utPkiTriggerResult() = BOOLEAN(true); - to_all_upper_ports(ut_pki_results, p_params); - } else { - // Encode UpperTester PDU - OCTETSTRING data; - _codec.encode(send_par, data); - // Update parameters - send_data(data, p_params); - } -} - -void uppertester_pki_layer::send_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_pki_layer::send_data: ", data); - // params.log(); - send_to_all_layers(data, p_params); -} - -void uppertester_pki_layer::receive_data(OCTETSTRING &data, params &p_params) { - loggers::get_instance().log_msg(">>> uppertester_pki_layer::receive_data: ", data); - - std::unique_ptr r = _codec.decode(data); - if (r.get() != nullptr) { - // Pass it to the ports if any - to_all_upper_ports(*r, p_params); - } -} - -uppertester_pki_layer_factory uppertester_pki_layer_factory::_f; +#include "uppertester_pki_layer_factory.hh" + +#include "LibItsPki_TestSystem.hh" +#include "LibItsPki_TypesAndValues.hh" + +#include "loggers.hh" + +uppertester_pki_layer::uppertester_pki_layer(const std::string &p_type, const std::string ¶m) + : t_layer(p_type), _params(), _codec() { + loggers::get_instance().log(">>> uppertester_pki_layer::uppertester_pki_layer: %s, %s", to_string().c_str(), param.c_str()); + // Setup parameters + params::convert(_params, param); + params::const_iterator it = _params.find(params::loopback); + if (it == _params.cend()) { + _params.insert(std::pair(params::loopback, "0")); + } +} + +void uppertester_pki_layer::sendMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_pki_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsPki__TypesAndValues::UtPkiResults ut_pki_results; + ut_pki_results.utPkiInitializeResult() = BOOLEAN(true); + to_all_upper_ports(ut_pki_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode((const Record_Type &)send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_pki_layer::sendMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_pki_layer::sendMsg", send_par); + + if (_params[params::loopback].compare("1") == 0) { + LibItsPki__TypesAndValues::UtPkiResults ut_pki_results; + ut_pki_results.utPkiTriggerResult() = BOOLEAN(true); + to_all_upper_ports(ut_pki_results, p_params); + } else { + // Encode UpperTester PDU + OCTETSTRING data; + _codec.encode(send_par, data); + // Update parameters + send_data(data, p_params); + } +} + +void uppertester_pki_layer::send_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_pki_layer::send_data: ", data); + // params.log(); + send_to_all_layers(data, p_params); +} + +void uppertester_pki_layer::receive_data(OCTETSTRING &data, params &p_params) { + loggers::get_instance().log_msg(">>> uppertester_pki_layer::receive_data: ", data); + + std::unique_ptr r = _codec.decode(data); + if (r.get() != nullptr) { + // Pass it to the ports if any + to_all_upper_ports(*r, p_params); + } +} + +uppertester_pki_layer_factory uppertester_pki_layer_factory::_f; diff --git a/ccsrc/Protocols/UpperTester/uppertester_pki_layer.hh b/ccsrc/Protocols/UpperTester/uppertester_pki_layer.hh index 9d482f1d69b9343c96af88804ec08a55a9f16ccb..7dc91e1308f6d6e6d8ba881470b27cf4c69369f5 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_pki_layer.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_pki_layer.hh @@ -1,41 +1,41 @@ -/*! - * \file uppertester_pki_layer.hh - * \brief Header file for ITS UpperTester PKI protocol layer definition. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include - -#include "t_layer.hh" -#include "uppertester_pki_codec.hh" - -namespace LibItsPki__TestSystem { - class UpperTesterPkiPort; -} - -namespace LibItsPki__TypesAndValues { - class UtPkiInitialize; - class UtPkiTrigger; -} // namespace LibItsPki__TypesAndValues - -class uppertester_pki_layer : public t_layer { - params _params; - uppertester_pki_codec _codec; - -public: - uppertester_pki_layer() : t_layer(), _params(), _codec(){}; - uppertester_pki_layer(const std::string &p_type, const std::string ¶m); - virtual ~uppertester_pki_layer(){}; - - void sendMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par, params &p_params); - void sendMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par, params &p_params); - - virtual void send_data(OCTETSTRING &data, params &p_params); - virtual void receive_data(OCTETSTRING &data, params &info); -}; // End of class uppertester_pki_layer +/*! + * \file uppertester_pki_layer.hh + * \brief Header file for ITS UpperTester PKI protocol layer definition. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include + +#include "t_layer.hh" +#include "uppertester_pki_codec.hh" + +namespace LibItsPki__TestSystem { + class UpperTesterPkiPort; +} + +namespace LibItsPki__TypesAndValues { + class UtPkiInitialize; + class UtPkiTrigger; +} // namespace LibItsPki__TypesAndValues + +class uppertester_pki_layer : public t_layer { + params _params; + uppertester_pki_codec _codec; + +public: + uppertester_pki_layer() : t_layer(), _params(), _codec(){}; + uppertester_pki_layer(const std::string &p_type, const std::string ¶m); + virtual ~uppertester_pki_layer(){}; + + void sendMsg(const LibItsPki__TypesAndValues::UtPkiInitialize &send_par, params &p_params); + void sendMsg(const LibItsPki__TypesAndValues::UtPkiTrigger &send_par, params &p_params); + + virtual void send_data(OCTETSTRING &data, params &p_params); + virtual void receive_data(OCTETSTRING &data, params &info); +}; // End of class uppertester_pki_layer diff --git a/ccsrc/Protocols/UpperTester/uppertester_pki_layer_factory.hh b/ccsrc/Protocols/UpperTester/uppertester_pki_layer_factory.hh index 4fb1b40c12e574cfafefaa658eee909e40127483..f7026b44b3b97ddca23f14cdd8848313ffeb474c 100644 --- a/ccsrc/Protocols/UpperTester/uppertester_pki_layer_factory.hh +++ b/ccsrc/Protocols/UpperTester/uppertester_pki_layer_factory.hh @@ -1,26 +1,26 @@ -/*! - * \file uppertester_pki_layer_factory.hh - * \brief Header file for ITS PKI Upper Tester protocol layer factory. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include "layer_stack_builder.hh" - -#include "uppertester_pki_layer.hh" - -class uppertester_pki_layer_factory : public layer_factory { - static uppertester_pki_layer_factory _f; - -public: - uppertester_pki_layer_factory() { - // Register factory - layer_stack_builder::register_layer_factory("UT_PKI", this); - }; - inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_pki_layer(p_type, p_param); }; -}; // End of class uppertester_pki_layer_factory +/*! + * \file uppertester_pki_layer_factory.hh + * \brief Header file for ITS PKI Upper Tester protocol layer factory. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include "layer_stack_builder.hh" + +#include "uppertester_pki_layer.hh" + +class uppertester_pki_layer_factory : public layer_factory { + static uppertester_pki_layer_factory _f; + +public: + uppertester_pki_layer_factory() { + // Register factory + layer_stack_builder::register_layer_factory("UT_PKI", this); + }; + inline virtual layer *create_layer(const std::string &p_type, const std::string &p_param) { return new uppertester_pki_layer(p_type, p_param); }; +}; // End of class uppertester_pki_layer_factory diff --git a/ccsrc/geospacial/geospacial.cc b/ccsrc/geospacial/geospacial.cc index 1dbf7df7c4e983a09fe1e425d17376ef4b90cac1..c1163c49186ec5b6bbf1e70c753ff4d48281a77d 100644 --- a/ccsrc/geospacial/geospacial.cc +++ b/ccsrc/geospacial/geospacial.cc @@ -1,192 +1,192 @@ -#include "geospacial.hh" - -coordinates::coordinates() { - latitude = .0; - longitude = .0; - altitude = .0; -} - -coordinates::coordinates(const double p_latitude, const double p_longitude, const double p_altitude) { - latitude = p_latitude; - longitude = p_longitude; - altitude = p_altitude; -} - -const bool coordinates::is_valid_coordinates() const { - if (latitude > -90.0L && latitude < 90.L && longitude > -180.0L && longitude < 180L) { - return true; - } else if (latitude > -HALFPI && latitude < HALFPI && longitude > -PI && longitude < PI) { - return true; - } - return false; -} - -const double coordinates::distance_less_than_1km(const coordinates &p) const { // this position has origin - double a = HALFPI - latitude; - double b = HALFPI - p.latitude; - double c = sqrt(a * a + b * b - 2 * a * b * cos(p.longitude - longitude)); - return (double)(R * c); -} - -const double coordinates::distance(const coordinates &p) const { // this position has origin - double dlon = p.longitude - longitude; - double dlat = p.latitude - latitude; - double s1 = sin(dlat / 2); - double s2 = sin(dlon / 2); - double a = (s1 * s1) + cos(latitude) * cos(p.latitude) * (s2 * s2); - double c = 2 * asin(std::min((double)1.0L, sqrt(a))); - return (double)(R * c); -} - -point::point() { - x = .0; - y = .0; - z = .0; -} - -point::point(const double p_x, const double p_y, const double p_z) { - x = p_x; - y = p_y; - z = p_z; -} - -int geospacial::load_countries_map(const std::string &p_file) { - std::ifstream ifs; - ifs.open(p_file); - if (ifs.fail()) { - ifs.close(); - return -1; - } - - Json::CharReaderBuilder builder; - builder["collectComments"] = true; - JSONCPP_STRING errs; - Json::Value root; - if (!parseFromStream(builder, ifs, &root, &errs)) { - std::cerr << errs << std::endl; - ifs.close(); - return -1; - } - // Get the value of the member of root named 'encoding', return a 'null' value if there is no such member. - const Json::Value plugins = root["features"]; - for (Json::Value::const_iterator it = plugins.begin(); it != plugins.end(); it++) { - const Json::Value v = *it; - Json::Value::Members m = v.getMemberNames(); - std::string key; - std::vector coord; - for (std::vector::const_iterator i = m.cbegin(); i != m.cend(); ++i) { - if (std::string(*i).compare("properties") == 0) { - key = process_properties(v[*i]); - } else if (std::string(*i).compare("geometry") == 0) { - coord = process_geometry(v[*i]); - } - } - std::pair>::iterator, bool> ret = _countries.insert(std::pair>(key, coord)); - if (ret.second == false) { - // Element already exist, add update it - // std::cerr << "element already existed: " << key << " - " << coord.size() << std::endl; - _countries[key].insert(_countries[key].end(), coord.begin(), coord.end()); - } - } // End of 'for' statement - ifs.close(); - - return 0; -} - -const int geospacial::is_in_country(const std::string &p_country, const coordinates &p_position) { - if (_countries.size() == 0) { - return -1; - } - std::map>::const_iterator it = _countries.find(p_country); - if (it == _countries.cend()) { - return -1; - } - - point p = wgs84_to_point(p_position.latitude, p_position.longitude); - for (auto ik = it->second.cbegin(); ik != it->second.cend(); ++ik) { - if (is_inside_polygon(*ik, p) == 0) { - return 0; - } - } // End of 'for' statement - - return -1; -} - -const std::string geospacial::process_properties(const Json::Value p_properties) { return p_properties["iso_n3"].asString(); } - -const std::vector geospacial::process_geometry(const Json::Value p_geometry) { - std::vector ar; - for (Json::Value::const_iterator it = p_geometry["coordinates"].begin(); it != p_geometry["coordinates"].end(); it++) { - std::vector polygons = extract_polygons(*it); - ar.insert(ar.end(), polygons.begin(), polygons.end()); - } - - return ar; -} - -const std::vector geospacial::extract_polygons(const Json::Value p_polygon) { - std::vector l; - Json::Value::const_iterator it = p_polygon.begin(); - Json::Value::const_iterator ik = static_cast(*it).begin(); - if (static_cast(*ik).isArray()) { - l = extract_polygons(*it); - } else if (static_cast(*ik).isDouble()) { - polygon p; - for (; it != p_polygon.end(); it++) { - ik = static_cast(*it).begin(); - coordinates c(static_cast(*++ik).asDouble(), // latitude - static_cast(*ik).asDouble(), // longitude - .0); - p.push_back(std::make_tuple(c, wgs84_to_point(c.latitude, c.longitude))); - } // End of 'for' statement - l.push_back(p); - } else { - std::cerr << "extract_polygons: wrong type" << std::endl; - } - - return l; -} - -const point geospacial::wgs84_to_point(const double p_latitude, const double p_longitude) const { - double latitude_rad = p_latitude * PI / 180.0L; - double longitude_rad = p_longitude * PI / 180.0L; - return point((double)(R * cos(latitude_rad) * cos(longitude_rad)), (double)(R * cos(latitude_rad) * sin(longitude_rad)), (double)(R * sin(latitude_rad))); -} - -const int geospacial::is_inside_polygon(const polygon &p_polygon, const point &q) const { - int i; - double angle = .0L; - point p1; - point p2; - int n = p_polygon.size(); - - for (i = 0; i < n; i++) { - // std::clog << "is_inside_polygon: Processing vertex " << i << " -> " << (i + 1) % n << std::endl; - point p = std::get<1>(p_polygon[i]); - point pnext = std::get<1>(p_polygon[(i + 1) % n]); - p1.x = p.x - q.x; - p1.y = p.y - q.y; - p2.x = pnext.x - q.x; - p2.y = pnext.y - q.y; - angle += CalcAngleSum_2d(p1, p2); - // std::clog << "is_inside_polygon: New angle " << angle << std::endl; - } - // std::clog << "is_inside_polygon: Final angle " << fabs(angle) << std::endl; - - if (fabs(angle) < PI) - return -1; - else - return 0; -} - -const double geospacial::CalcAngleSum_2d(const point &p1, const point &p2) const { - double theta1 = atan2(p1.y, p1.x); - double theta2 = atan2(p2.y, p2.x); - double dtheta = theta2 - theta1; - while (dtheta > PI) - dtheta -= TWOPI; - while (dtheta < -PI) - dtheta += TWOPI; - - return (dtheta); -} +#include "geospacial.hh" + +coordinates::coordinates() { + latitude = .0; + longitude = .0; + altitude = .0; +} + +coordinates::coordinates(const double p_latitude, const double p_longitude, const double p_altitude) { + latitude = p_latitude; + longitude = p_longitude; + altitude = p_altitude; +} + +const bool coordinates::is_valid_coordinates() const { + if (latitude > -90.0L && latitude < 90.L && longitude > -180.0L && longitude < 180L) { + return true; + } else if (latitude > -HALFPI && latitude < HALFPI && longitude > -PI && longitude < PI) { + return true; + } + return false; +} + +const double coordinates::distance_less_than_1km(const coordinates &p) const { // this position has origin + double a = HALFPI - latitude; + double b = HALFPI - p.latitude; + double c = sqrt(a * a + b * b - 2 * a * b * cos(p.longitude - longitude)); + return (double)(R * c); +} + +const double coordinates::distance(const coordinates &p) const { // this position has origin + double dlon = p.longitude - longitude; + double dlat = p.latitude - latitude; + double s1 = sin(dlat / 2); + double s2 = sin(dlon / 2); + double a = (s1 * s1) + cos(latitude) * cos(p.latitude) * (s2 * s2); + double c = 2 * asin(std::min((double)1.0L, sqrt(a))); + return (double)(R * c); +} + +point::point() { + x = .0; + y = .0; + z = .0; +} + +point::point(const double p_x, const double p_y, const double p_z) { + x = p_x; + y = p_y; + z = p_z; +} + +int geospacial::load_countries_map(const std::string &p_file) { + std::ifstream ifs; + ifs.open(p_file); + if (ifs.fail()) { + ifs.close(); + return -1; + } + + Json::CharReaderBuilder builder; + builder["collectComments"] = true; + JSONCPP_STRING errs; + Json::Value root; + if (!parseFromStream(builder, ifs, &root, &errs)) { + std::cerr << errs << std::endl; + ifs.close(); + return -1; + } + // Get the value of the member of root named 'encoding', return a 'null' value if there is no such member. + const Json::Value plugins = root["features"]; + for (Json::Value::const_iterator it = plugins.begin(); it != plugins.end(); it++) { + const Json::Value v = *it; + Json::Value::Members m = v.getMemberNames(); + std::string key; + std::vector coord; + for (std::vector::const_iterator i = m.cbegin(); i != m.cend(); ++i) { + if (std::string(*i).compare("properties") == 0) { + key = process_properties(v[*i]); + } else if (std::string(*i).compare("geometry") == 0) { + coord = process_geometry(v[*i]); + } + } + std::pair>::iterator, bool> ret = _countries.insert(std::pair>(key, coord)); + if (ret.second == false) { + // Element already exist, add update it + // std::cerr << "element already existed: " << key << " - " << coord.size() << std::endl; + _countries[key].insert(_countries[key].end(), coord.begin(), coord.end()); + } + } // End of 'for' statement + ifs.close(); + + return 0; +} + +const int geospacial::is_in_country(const std::string &p_country, const coordinates &p_position) { + if (_countries.size() == 0) { + return -1; + } + std::map>::const_iterator it = _countries.find(p_country); + if (it == _countries.cend()) { + return -1; + } + + point p = wgs84_to_point(p_position.latitude, p_position.longitude); + for (auto ik = it->second.cbegin(); ik != it->second.cend(); ++ik) { + if (is_inside_polygon(*ik, p) == 0) { + return 0; + } + } // End of 'for' statement + + return -1; +} + +const std::string geospacial::process_properties(const Json::Value p_properties) { return p_properties["iso_n3"].asString(); } + +const std::vector geospacial::process_geometry(const Json::Value p_geometry) { + std::vector ar; + for (Json::Value::const_iterator it = p_geometry["coordinates"].begin(); it != p_geometry["coordinates"].end(); it++) { + std::vector polygons = extract_polygons(*it); + ar.insert(ar.end(), polygons.begin(), polygons.end()); + } + + return ar; +} + +const std::vector geospacial::extract_polygons(const Json::Value p_polygon) { + std::vector l; + Json::Value::const_iterator it = p_polygon.begin(); + Json::Value::const_iterator ik = static_cast(*it).begin(); + if (static_cast(*ik).isArray()) { + l = extract_polygons(*it); + } else if (static_cast(*ik).isDouble()) { + polygon p; + for (; it != p_polygon.end(); it++) { + ik = static_cast(*it).begin(); + coordinates c(static_cast(*++ik).asDouble(), // latitude + static_cast(*ik).asDouble(), // longitude + .0); + p.push_back(std::make_tuple(c, wgs84_to_point(c.latitude, c.longitude))); + } // End of 'for' statement + l.push_back(p); + } else { + std::cerr << "extract_polygons: wrong type" << std::endl; + } + + return l; +} + +const point geospacial::wgs84_to_point(const double p_latitude, const double p_longitude) const { + double latitude_rad = p_latitude * PI / 180.0L; + double longitude_rad = p_longitude * PI / 180.0L; + return point((double)(R * cos(latitude_rad) * cos(longitude_rad)), (double)(R * cos(latitude_rad) * sin(longitude_rad)), (double)(R * sin(latitude_rad))); +} + +const int geospacial::is_inside_polygon(const polygon &p_polygon, const point &q) const { + int i; + double angle = .0L; + point p1; + point p2; + int n = p_polygon.size(); + + for (i = 0; i < n; i++) { + // std::clog << "is_inside_polygon: Processing vertex " << i << " -> " << (i + 1) % n << std::endl; + point p = std::get<1>(p_polygon[i]); + point pnext = std::get<1>(p_polygon[(i + 1) % n]); + p1.x = p.x - q.x; + p1.y = p.y - q.y; + p2.x = pnext.x - q.x; + p2.y = pnext.y - q.y; + angle += CalcAngleSum_2d(p1, p2); + // std::clog << "is_inside_polygon: New angle " << angle << std::endl; + } + // std::clog << "is_inside_polygon: Final angle " << fabs(angle) << std::endl; + + if (fabs(angle) < PI) + return -1; + else + return 0; +} + +const double geospacial::CalcAngleSum_2d(const point &p1, const point &p2) const { + double theta1 = atan2(p1.y, p1.x); + double theta2 = atan2(p2.y, p2.x); + double dtheta = theta2 - theta1; + while (dtheta > PI) + dtheta -= TWOPI; + while (dtheta < -PI) + dtheta += TWOPI; + + return (dtheta); +} diff --git a/ccsrc/geospacial/geospacial.hh b/ccsrc/geospacial/geospacial.hh index f521561ebe693416966335d8bb3924884bb8c980..0862e0dceab3afeaa4d5248a1cae72760a460f72 100644 --- a/ccsrc/geospacial/geospacial.hh +++ b/ccsrc/geospacial/geospacial.hh @@ -1,65 +1,65 @@ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#define EPSILON 0.0000001 -#define MODULUS(p) (sqrt(p.x * p.x + p.y * p.y + p.z * p.z)) -#define PI 3.1415926535897932384626435 -#define HALFPI 1.5707963267948966192313216916398 -#define TWOPI 6.283185307179586476925287 -//#define RTOD 57.2957795 -#define R 6378140.0 // Radius of the earth in meters - -class coordinates { -public: - double latitude; - double longitude; - double altitude; - -public: - coordinates(); - coordinates(const double p_latitude, const double p_longitude, const double p_altitude); - virtual ~coordinates(){}; - inline const coordinates to_radian() const { return coordinates(latitude * PI / 180, longitude * PI / 180, altitude); }; - const bool is_valid_coordinates() const; - ; - const double distance_less_than_1km(const coordinates &p) const; // this position has origin - const double distance(const coordinates &p) const; // this position has origin -}; - -class point { -public: - double x, y, z; - -public: - point(); - point(const double p_x, const double p_y, const double p_z); -}; - -typedef std::vector> polygon; - -class geospacial { - std::map> _countries; - const point wgs84_to_point(const double p_latitude, const double p_longitude) const; - const std::string process_properties(const Json::Value p_properties); - const std::vector process_geometry(const Json::Value p_geometry); - const std::vector extract_polygons(const Json::Value p_polygon); - const double CalcAngleSum_2d(const point &p1, const point &p2) const; - const int is_inside_polygon(const polygon &p_polygon, const point &q) const; - -public: - geospacial(){}; - virtual ~geospacial(){}; - int load_countries_map(const std::string &p_file); - const int is_in_country(const std::string &p_country, const coordinates &p_position); -}; +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#define EPSILON 0.0000001 +#define MODULUS(p) (sqrt(p.x * p.x + p.y * p.y + p.z * p.z)) +#define PI 3.1415926535897932384626435 +#define HALFPI 1.5707963267948966192313216916398 +#define TWOPI 6.283185307179586476925287 +//#define RTOD 57.2957795 +#define R 6378140.0 // Radius of the earth in meters + +class coordinates { +public: + double latitude; + double longitude; + double altitude; + +public: + coordinates(); + coordinates(const double p_latitude, const double p_longitude, const double p_altitude); + virtual ~coordinates(){}; + inline const coordinates to_radian() const { return coordinates(latitude * PI / 180, longitude * PI / 180, altitude); }; + const bool is_valid_coordinates() const; + ; + const double distance_less_than_1km(const coordinates &p) const; // this position has origin + const double distance(const coordinates &p) const; // this position has origin +}; + +class point { +public: + double x, y, z; + +public: + point(); + point(const double p_x, const double p_y, const double p_z); +}; + +typedef std::vector> polygon; + +class geospacial { + std::map> _countries; + const point wgs84_to_point(const double p_latitude, const double p_longitude) const; + const std::string process_properties(const Json::Value p_properties); + const std::vector process_geometry(const Json::Value p_geometry); + const std::vector extract_polygons(const Json::Value p_polygon); + const double CalcAngleSum_2d(const point &p1, const point &p2) const; + const int is_inside_polygon(const polygon &p_polygon, const point &q) const; + +public: + geospacial(){}; + virtual ~geospacial(){}; + int load_countries_map(const std::string &p_file); + const int is_in_country(const std::string &p_country, const coordinates &p_position); +}; diff --git a/ccsrc/geospacial/module.mk b/ccsrc/geospacial/module.mk index 5a05a64ea7ec63fc5aefc47ed400c0a673eba024..447dc3a993f0ac323f55ad2c391665169883a0c4 100644 --- a/ccsrc/geospacial/module.mk +++ b/ccsrc/geospacial/module.mk @@ -1,3 +1,3 @@ -sources := geospacial.cc -includes := . - +sources := geospacial.cc +includes := . + diff --git a/ccsrc/loggers/loggers.cc b/ccsrc/loggers/loggers.cc index fba1c590dcc06cec73dab5da72c84f2e37888c75..be5285a625647e68e1f65ae3ca342fd5364daccf 100644 --- a/ccsrc/loggers/loggers.cc +++ b/ccsrc/loggers/loggers.cc @@ -1,4 +1,4 @@ -#include "loggers.hh" - -std::unique_ptr loggers::_instance = static_cast>(new loggers); - +#include "loggers.hh" + +std::unique_ptr loggers::_instance = static_cast>(new loggers); + diff --git a/ccsrc/loggers/loggers.hh b/ccsrc/loggers/loggers.hh index 743390d2d7b163bee1df4447083ae1857e4e2e03..36f73449dee9fa01d1b96b3f5cc18ffa1119c557 100644 --- a/ccsrc/loggers/loggers.hh +++ b/ccsrc/loggers/loggers.hh @@ -1,273 +1,273 @@ -/*! - * \file loogers.hh - * \brief Header file for the logger framework. - * \author ETSI STF525 - * \copyright ETSI Copyright Notification - * No part may be reproduced except as authorized by written permission. - * The copyright and the foregoing restriction extend to reproduction in all media. - * All rights reserved. - * \version 0.1 - */ -#pragma once - -#include -#include -#include -#include -#include - -/** -class Base_Type; -class OCTETSTRING; -class TTCN_Buffer; -class TTCN_Logger; -enum TTCN_Logger::Severity; -extern void TTCN_error(const char *err_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2), __noreturn__)); -extern void TTCN_error_begin(const char *err_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2))); -extern void TTCN_error_end() __attribute__ ((__noreturn__)); -void TTCN_warning(const char *warning_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2))); -extern void TTCN_warning_begin(const char *warning_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2))); -extern void TTCN_warning_end(); -**/ - -using namespace std; // Required for isnan() -#include - -/*! - * \class loggers - * \brief This class provides basic functionalities for an ITS dictionary - * \implements Singleton pattern - * \todo Remove reference to TTCN3.hh - */ -class loggers { -private: //! \privatesection - static std::unique_ptr _instance; //! Smart pointer to the unique instance of the logger framework - std::map - _times; //! Timer used to measure execution time between calls to methods \loggers::set_start_time and \loggers::set_stop_time - - /*! - * \brief Default constructor - * Create a new instance of the loggers class - * \private - */ - explicit loggers() : _times(){}; - - inline void log_time_exec(const char *p_fmt, ...); - -public: //! \publicsection - /*! - * \brief Default destructor - */ - virtual ~loggers(){}; - - /*! - * \fn static loggers& get_instance(); - * \brief Accessor for the unique instance of the logger framework - * \inline - */ - static inline loggers &get_instance() { return *_instance.get(); }; - - /*! - * \fn void log_to_hexa(const char *p_prompt, const TTCN_Buffer& buffer); - * \brief Hexa dump of the \see TTCN_Buffer buffer - * \param[in] p_prompt Label of the log to be produced - * \param[in] buffer The TTCN_Buffer buffer to dump - * \inline - */ - inline void log_to_hexa(const char *p_prompt, const TTCN_Buffer &buffer); - /*! - * \fn void log_to_hexa(const char *p_prompt, const OCTETSTRING& msg); - * \brief Hexa dump of the \see OCTETSTRING buffer - * \param[in] p_prompt Label of the log to be produced - * \param[in] msg The OCTETSTRING buffer to dump - * \inline - */ - inline void log_to_hexa(const char *p_prompt, const OCTETSTRING &msg); - /*! - * \fn void log_to_hexa(const char *p_prompt, const unsigned char* msg, const size_t msg_size); - * \brief Hexa dump of the provided buffer - * \param[in] p_prompt Label of the log to be produced - * \param[in] msg The buffer to dump - * \inline - */ - inline void log_to_hexa(const char *p_prompt, const unsigned char *msg, const size_t msg_size); - /*! - * \fn void log_msg(const char *p_prompt, const Base_Type& p_type); - * \brief Debug log of TITAN data structures - * \param[in] p_prompt Label of the log to be produced - * \param[in] msg The TITAN data structure to log - * \inline - */ - inline void log_msg(const char *p_prompt, const Base_Type &p_type); - /*! - * \fn void log(const char *p_fmt, ...); - * \brief Debug message based on printf-compliant formatting message - * \param[in] p_fmt The printf-compliant format of the message to log - * \param[in] ... The arguments - * \inline - */ - inline void log(const char *p_fmt, ...); - - /*! - * \fn void user_msg(const char *p_prompt, const Base_Type& p_type); - * \brief User message of TITAN data structures - * \param[in] p_prompt Label of the log to be produced - * \param[in] msg The TITAN data structure to log - * \inline - */ - inline void user_msg(const char *p_prompt, const Base_Type &p_type); - /*! - * \fn void user(const char *p_fmt, ...); - * \brief User message based on printf-compliant formatting message - * \param[in] p_fmt The printf-compliant format of the message to log - * \param[in] ... The arguments - * \inline - */ - inline void user(const char *p_fmt, ...); - - /*! - * \fn void user_msg(const char *p_prompt, const Base_Type& p_type); - * \brief Warning message of TITAN data structures - * \param[in] p_prompt Label of the log to be produced - * \param[in] msg The TITAN data structure to log - * \inline - */ - inline void warning_msg(const char *p_prompt, const Base_Type &p_type); - /*! - * \fn void user(const char *p_fmt, ...); - * \brief Warning message based on printf-compliant formatting message - * \param[in] p_fmt The printf-compliant format of the message to log - * \param[in] ... The arguments - * \inline - */ - inline void warning(const char *p_fmt, ...); - - /*! - * \fn void user(const char *p_fmt, ...); - * \brief Error message based on printf-compliant formatting message - * \param[in] p_fmt The printf-compliant format of the message to log - * \param[in] ... The arguments - * \inline - */ - inline void error(const char *p_fmt, ...); - - /*! - * \fn void set_start_time(std::string& p_time_key); - * \brief Start execution time measurement - * \param[in] p_time_key A timer identifier (any string) - * \inline - */ - inline void set_start_time(std::string &p_time_key); - /*! - * \fn void set_stop_time(std::string& p_time_key, float& p_time); - * \brief Stop execution time measurement - * \param[in] p_time_key The timer identifier provided while calling \see loggers::set_start_time method - * \param[out] p_time The execution time measured in milliseconds - * \inline - */ - inline void set_stop_time(std::string &p_time_key, float &p_time); -}; // End of class loggers - -void loggers::log_to_hexa(const char *p_prompt, const TTCN_Buffer &buffer) { - TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); - TTCN_Logger::log_event_str(p_prompt); - buffer.log(); - TTCN_Logger::end_event(); -} - -void loggers::log_to_hexa(const char *p_prompt, const OCTETSTRING &msg) { - TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); - TTCN_Logger::log_event_str(p_prompt); - TTCN_Logger::log_event("Size: %d,\nMsg: ", msg.lengthof()); - - for (int i = 0; i < msg.lengthof(); i++) { - TTCN_Logger::log_event(" %02x", ((const unsigned char *)msg)[i]); - } - TTCN_Logger::log_event("\n"); - TTCN_Logger::end_event(); -} - -void loggers::log_to_hexa(const char *p_prompt, const unsigned char *msg, const size_t msg_size) { - TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); - TTCN_Logger::log_event_str(p_prompt); - for (size_t i = 0; i < msg_size; i++) { - TTCN_Logger::log_event(" %02x", *(msg + i)); - } - TTCN_Logger::log_event("\n"); - TTCN_Logger::end_event(); -} - -void loggers::log_msg(const char *p_prompt, const Base_Type &p_type) { - TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); - TTCN_Logger::log_event_str(p_prompt); - p_type.log(); - TTCN_Logger::end_event(); -} - -void loggers::log(const char *p_fmt, ...) { - TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); - va_list args; - va_start(args, p_fmt); - TTCN_Logger::log_event_va_list(p_fmt, args); - va_end(args); - TTCN_Logger::end_event(); -} - -void loggers::user_msg(const char *p_prompt, const Base_Type &p_type) { - TTCN_Logger::begin_event(TTCN_Logger::USER_UNQUALIFIED); - TTCN_Logger::log_event_str(p_prompt); - p_type.log(); - TTCN_Logger::end_event(); -} - -void loggers::user(const char *p_fmt, ...) { - TTCN_Logger::begin_event(TTCN_Logger::USER_UNQUALIFIED); - va_list args; - va_start(args, p_fmt); - TTCN_Logger::log_event_va_list(p_fmt, args); - va_end(args); - TTCN_Logger::end_event(); -} - -void loggers::warning(const char *p_fmt, ...) { - TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED); - va_list args; - va_start(args, p_fmt); - TTCN_Logger::log_event_va_list(p_fmt, args); - va_end(args); - TTCN_Logger::end_event(); -} - -void loggers::warning_msg(const char *p_prompt, const Base_Type &p_type) { - TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED); - TTCN_Logger::log_event_str(p_prompt); - p_type.log(); - TTCN_Logger::end_event(); -} - -void loggers::error(const char *p_fmt, ...) { - va_list args; - va_start(args, p_fmt); - TTCN_error(p_fmt, args); - va_end(args); -} - -void loggers::set_start_time(std::string &p_time_key) { _times[p_time_key] = std::clock(); } - -void loggers::set_stop_time(std::string &p_time_key, float &p_time) { - std::map::iterator it = _times.find(p_time_key); - if (it != loggers::_times.end()) { - p_time = (std::clock() - _times[p_time_key]) * 1000.0 / CLOCKS_PER_SEC; // in milliseconds - _times.erase(it); - loggers::get_instance().log_time_exec("%s: Execution duration: %f ms", p_time_key.c_str(), p_time); - } -} - -void loggers::log_time_exec(const char *p_fmt, ...) { - TTCN_Logger::begin_event(TTCN_Logger::EXECUTOR_RUNTIME); - va_list args; - va_start(args, p_fmt); - TTCN_Logger::log_event_va_list(p_fmt, args); - va_end(args); - TTCN_Logger::end_event(); -} +/*! + * \file loogers.hh + * \brief Header file for the logger framework. + * \author ETSI STF525 + * \copyright ETSI Copyright Notification + * No part may be reproduced except as authorized by written permission. + * The copyright and the foregoing restriction extend to reproduction in all media. + * All rights reserved. + * \version 0.1 + */ +#pragma once + +#include +#include +#include +#include +#include + +/** +class Base_Type; +class OCTETSTRING; +class TTCN_Buffer; +class TTCN_Logger; +enum TTCN_Logger::Severity; +extern void TTCN_error(const char *err_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2), __noreturn__)); +extern void TTCN_error_begin(const char *err_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2))); +extern void TTCN_error_end() __attribute__ ((__noreturn__)); +void TTCN_warning(const char *warning_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2))); +extern void TTCN_warning_begin(const char *warning_msg, ...) __attribute__ ((__format__ (__printf__, 1, 2))); +extern void TTCN_warning_end(); +**/ + +using namespace std; // Required for isnan() +#include + +/*! + * \class loggers + * \brief This class provides basic functionalities for an ITS dictionary + * \implements Singleton pattern + * \todo Remove reference to TTCN3.hh + */ +class loggers { +private: //! \privatesection + static std::unique_ptr _instance; //! Smart pointer to the unique instance of the logger framework + std::map + _times; //! Timer used to measure execution time between calls to methods \loggers::set_start_time and \loggers::set_stop_time + + /*! + * \brief Default constructor + * Create a new instance of the loggers class + * \private + */ + explicit loggers() : _times(){}; + + inline void log_time_exec(const char *p_fmt, ...); + +public: //! \publicsection + /*! + * \brief Default destructor + */ + virtual ~loggers(){}; + + /*! + * \fn static loggers& get_instance(); + * \brief Accessor for the unique instance of the logger framework + * \inline + */ + static inline loggers &get_instance() { return *_instance.get(); }; + + /*! + * \fn void log_to_hexa(const char *p_prompt, const TTCN_Buffer& buffer); + * \brief Hexa dump of the \see TTCN_Buffer buffer + * \param[in] p_prompt Label of the log to be produced + * \param[in] buffer The TTCN_Buffer buffer to dump + * \inline + */ + inline void log_to_hexa(const char *p_prompt, const TTCN_Buffer &buffer); + /*! + * \fn void log_to_hexa(const char *p_prompt, const OCTETSTRING& msg); + * \brief Hexa dump of the \see OCTETSTRING buffer + * \param[in] p_prompt Label of the log to be produced + * \param[in] msg The OCTETSTRING buffer to dump + * \inline + */ + inline void log_to_hexa(const char *p_prompt, const OCTETSTRING &msg); + /*! + * \fn void log_to_hexa(const char *p_prompt, const unsigned char* msg, const size_t msg_size); + * \brief Hexa dump of the provided buffer + * \param[in] p_prompt Label of the log to be produced + * \param[in] msg The buffer to dump + * \inline + */ + inline void log_to_hexa(const char *p_prompt, const unsigned char *msg, const size_t msg_size); + /*! + * \fn void log_msg(const char *p_prompt, const Base_Type& p_type); + * \brief Debug log of TITAN data structures + * \param[in] p_prompt Label of the log to be produced + * \param[in] msg The TITAN data structure to log + * \inline + */ + inline void log_msg(const char *p_prompt, const Base_Type &p_type); + /*! + * \fn void log(const char *p_fmt, ...); + * \brief Debug message based on printf-compliant formatting message + * \param[in] p_fmt The printf-compliant format of the message to log + * \param[in] ... The arguments + * \inline + */ + inline void log(const char *p_fmt, ...); + + /*! + * \fn void user_msg(const char *p_prompt, const Base_Type& p_type); + * \brief User message of TITAN data structures + * \param[in] p_prompt Label of the log to be produced + * \param[in] msg The TITAN data structure to log + * \inline + */ + inline void user_msg(const char *p_prompt, const Base_Type &p_type); + /*! + * \fn void user(const char *p_fmt, ...); + * \brief User message based on printf-compliant formatting message + * \param[in] p_fmt The printf-compliant format of the message to log + * \param[in] ... The arguments + * \inline + */ + inline void user(const char *p_fmt, ...); + + /*! + * \fn void user_msg(const char *p_prompt, const Base_Type& p_type); + * \brief Warning message of TITAN data structures + * \param[in] p_prompt Label of the log to be produced + * \param[in] msg The TITAN data structure to log + * \inline + */ + inline void warning_msg(const char *p_prompt, const Base_Type &p_type); + /*! + * \fn void user(const char *p_fmt, ...); + * \brief Warning message based on printf-compliant formatting message + * \param[in] p_fmt The printf-compliant format of the message to log + * \param[in] ... The arguments + * \inline + */ + inline void warning(const char *p_fmt, ...); + + /*! + * \fn void user(const char *p_fmt, ...); + * \brief Error message based on printf-compliant formatting message + * \param[in] p_fmt The printf-compliant format of the message to log + * \param[in] ... The arguments + * \inline + */ + inline void error(const char *p_fmt, ...); + + /*! + * \fn void set_start_time(std::string& p_time_key); + * \brief Start execution time measurement + * \param[in] p_time_key A timer identifier (any string) + * \inline + */ + inline void set_start_time(std::string &p_time_key); + /*! + * \fn void set_stop_time(std::string& p_time_key, float& p_time); + * \brief Stop execution time measurement + * \param[in] p_time_key The timer identifier provided while calling \see loggers::set_start_time method + * \param[out] p_time The execution time measured in milliseconds + * \inline + */ + inline void set_stop_time(std::string &p_time_key, float &p_time); +}; // End of class loggers + +void loggers::log_to_hexa(const char *p_prompt, const TTCN_Buffer &buffer) { + TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); + TTCN_Logger::log_event_str(p_prompt); + buffer.log(); + TTCN_Logger::end_event(); +} + +void loggers::log_to_hexa(const char *p_prompt, const OCTETSTRING &msg) { + TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); + TTCN_Logger::log_event_str(p_prompt); + TTCN_Logger::log_event("Size: %d,\nMsg: ", msg.lengthof()); + + for (int i = 0; i < msg.lengthof(); i++) { + TTCN_Logger::log_event(" %02x", ((const unsigned char *)msg)[i]); + } + TTCN_Logger::log_event("\n"); + TTCN_Logger::end_event(); +} + +void loggers::log_to_hexa(const char *p_prompt, const unsigned char *msg, const size_t msg_size) { + TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); + TTCN_Logger::log_event_str(p_prompt); + for (size_t i = 0; i < msg_size; i++) { + TTCN_Logger::log_event(" %02x", *(msg + i)); + } + TTCN_Logger::log_event("\n"); + TTCN_Logger::end_event(); +} + +void loggers::log_msg(const char *p_prompt, const Base_Type &p_type) { + TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); + TTCN_Logger::log_event_str(p_prompt); + p_type.log(); + TTCN_Logger::end_event(); +} + +void loggers::log(const char *p_fmt, ...) { + TTCN_Logger::begin_event(TTCN_Logger::DEBUG_UNQUALIFIED); + va_list args; + va_start(args, p_fmt); + TTCN_Logger::log_event_va_list(p_fmt, args); + va_end(args); + TTCN_Logger::end_event(); +} + +void loggers::user_msg(const char *p_prompt, const Base_Type &p_type) { + TTCN_Logger::begin_event(TTCN_Logger::USER_UNQUALIFIED); + TTCN_Logger::log_event_str(p_prompt); + p_type.log(); + TTCN_Logger::end_event(); +} + +void loggers::user(const char *p_fmt, ...) { + TTCN_Logger::begin_event(TTCN_Logger::USER_UNQUALIFIED); + va_list args; + va_start(args, p_fmt); + TTCN_Logger::log_event_va_list(p_fmt, args); + va_end(args); + TTCN_Logger::end_event(); +} + +void loggers::warning(const char *p_fmt, ...) { + TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED); + va_list args; + va_start(args, p_fmt); + TTCN_Logger::log_event_va_list(p_fmt, args); + va_end(args); + TTCN_Logger::end_event(); +} + +void loggers::warning_msg(const char *p_prompt, const Base_Type &p_type) { + TTCN_Logger::begin_event(TTCN_Logger::WARNING_UNQUALIFIED); + TTCN_Logger::log_event_str(p_prompt); + p_type.log(); + TTCN_Logger::end_event(); +} + +void loggers::error(const char *p_fmt, ...) { + va_list args; + va_start(args, p_fmt); + TTCN_error(p_fmt, args); + va_end(args); +} + +void loggers::set_start_time(std::string &p_time_key) { _times[p_time_key] = std::clock(); } + +void loggers::set_stop_time(std::string &p_time_key, float &p_time) { + std::map::iterator it = _times.find(p_time_key); + if (it != loggers::_times.end()) { + p_time = (std::clock() - _times[p_time_key]) * 1000.0 / CLOCKS_PER_SEC; // in milliseconds + _times.erase(it); + loggers::get_instance().log_time_exec("%s: Execution duration: %f ms", p_time_key.c_str(), p_time); + } +} + +void loggers::log_time_exec(const char *p_fmt, ...) { + TTCN_Logger::begin_event(TTCN_Logger::EXECUTOR_RUNTIME); + va_list args; + va_start(args, p_fmt); + TTCN_Logger::log_event_va_list(p_fmt, args); + va_end(args); + TTCN_Logger::end_event(); +} diff --git a/ccsrc/loggers/module.mk b/ccsrc/loggers/module.mk index c735f82e1383ff9c6f5adb160aad284a11784f6d..36b4b2ce93ac5ea01ae123c9181b55d0676530c6 100644 --- a/ccsrc/loggers/module.mk +++ b/ccsrc/loggers/module.mk @@ -1,3 +1,3 @@ -sources := loggers.cc -includes := . - +sources := loggers.cc +includes := . + diff --git a/config.mk b/config.mk index a9c3220139ae74eb2dc12fc280d61563a7450dd2..a53d762fb085e8a68fada33fbc9c8ddaedc342e5 100644 --- a/config.mk +++ b/config.mk @@ -1,9 +1,9 @@ -#TTCN3_DIR := /cygdrive/c/Tools/Titan -#ASN1C_PATH := ../../../../../asn1c-fillabs2 -#WPCAP_DLL_PATH := /cygdrive/c/windows/system32/npcap/wpcap.dll -#NPCAP_INCLUDE := /cygdrive/c/PROGRA~1/Npcap/sdk/include -#T3Q_PATH=./tools/t3q-v2.0.0b30 -#T3Q_CONFIG=t3q.cfg -#T3D_PATH=./tools/t3d-v2.0.0b30 -#T3D_CONFIG=t3d.cfg -#ITS_CONTAINER=../../../AtsDENM/lib/asn1/cdd/ITS_Container.asn +#TTCN3_DIR := /cygdrive/c/Tools/Titan +ASN1C_PATH := /home/yann/frameworks/asn1c.denis +#WPCAP_DLL_PATH := /cygdrive/c/windows/system32/npcap/wpcap.dll +#NPCAP_INCLUDE := /cygdrive/c/PROGRA~1/Npcap/sdk/include +#T3Q_PATH=./tools/t3q-v2.0.0b30 +#T3Q_CONFIG=t3q.cfg +#T3D_PATH=./tools/t3d-v2.0.0b30 +#T3D_CONFIG=t3d.cfg +#ITS_CONTAINER=../../../AtsDENM/lib/asn1/cdd/ITS_Container.asn diff --git a/ttcn/AtsBTP b/ttcn/AtsBTP index a059f9ee8d09534799991e168cbbb754f99789e2..8220384412a2ed89fb798e322a27ae8c1b71016e 160000 --- a/ttcn/AtsBTP +++ b/ttcn/AtsBTP @@ -1 +1 @@ -Subproject commit a059f9ee8d09534799991e168cbbb754f99789e2 +Subproject commit 8220384412a2ed89fb798e322a27ae8c1b71016e diff --git a/ttcn/AtsCAM b/ttcn/AtsCAM index d8de9c38a697eea3adaf2190cabbdd38a6017360..4db6d5eaa80300f0b2d3ae35b2e94dc077cbcfba 160000 --- a/ttcn/AtsCAM +++ b/ttcn/AtsCAM @@ -1 +1 @@ -Subproject commit d8de9c38a697eea3adaf2190cabbdd38a6017360 +Subproject commit 4db6d5eaa80300f0b2d3ae35b2e94dc077cbcfba diff --git a/ttcn/AtsDENM b/ttcn/AtsDENM index 8c1126b6f73d32404a5ffe2bd934be1f1583189c..122095b7d0b4b244d988d1e1afa6ddd427366fa1 160000 --- a/ttcn/AtsDENM +++ b/ttcn/AtsDENM @@ -1 +1 @@ -Subproject commit 8c1126b6f73d32404a5ffe2bd934be1f1583189c +Subproject commit 122095b7d0b4b244d988d1e1afa6ddd427366fa1 diff --git a/ttcn/AtsGeoNetworking b/ttcn/AtsGeoNetworking index 252a6d05fbd1af4ee139175e62446b4be8302392..55f6521c6ed265b559de411a72c8745f8c288b0a 160000 --- a/ttcn/AtsGeoNetworking +++ b/ttcn/AtsGeoNetworking @@ -1 +1 @@ -Subproject commit 252a6d05fbd1af4ee139175e62446b4be8302392 +Subproject commit 55f6521c6ed265b559de411a72c8745f8c288b0a diff --git a/ttcn/AtsIPv6OverGeoNetworking b/ttcn/AtsIPv6OverGeoNetworking index 8417319d0781f3ae53e64cb6c6cb0215dcd4342e..066a09ac1f915e76eb628d1501755196ec39ff47 160000 --- a/ttcn/AtsIPv6OverGeoNetworking +++ b/ttcn/AtsIPv6OverGeoNetworking @@ -1 +1 @@ -Subproject commit 8417319d0781f3ae53e64cb6c6cb0215dcd4342e +Subproject commit 066a09ac1f915e76eb628d1501755196ec39ff47 diff --git a/ttcn/AtsIS b/ttcn/AtsIS index adc3b59e499ea8ec55ba80b071733cf3e42113d5..114687d4224eb6bd9e39108c97721bccda8148d8 160000 --- a/ttcn/AtsIS +++ b/ttcn/AtsIS @@ -1 +1 @@ -Subproject commit adc3b59e499ea8ec55ba80b071733cf3e42113d5 +Subproject commit 114687d4224eb6bd9e39108c97721bccda8148d8 diff --git a/ttcn/AtsPki b/ttcn/AtsPki index 75e8752737c295153343116f64cbde4bfd9b8d41..3e012ed7ecf629bea279333ed44b1dc6bf15b435 160000 --- a/ttcn/AtsPki +++ b/ttcn/AtsPki @@ -1 +1 @@ -Subproject commit 75e8752737c295153343116f64cbde4bfd9b8d41 +Subproject commit 3e012ed7ecf629bea279333ed44b1dc6bf15b435 diff --git a/ttcn/AtsSecurity b/ttcn/AtsSecurity index 6ec60e1dff4d3b10a3aa98b8348acd39f7dfb6df..01db511bb895d1a56d8475c735775ba9acaf1232 160000 --- a/ttcn/AtsSecurity +++ b/ttcn/AtsSecurity @@ -1 +1 @@ -Subproject commit 6ec60e1dff4d3b10a3aa98b8348acd39f7dfb6df +Subproject commit 01db511bb895d1a56d8475c735775ba9acaf1232