]> git.ipfire.org Git - thirdparty/snort3.git/commitdiff
Merge pull request #690 in SNORT/snort3 from appid_optimize_loading_lua_detectors...
authorHui Cao (huica) <huica@cisco.com>
Wed, 2 Nov 2016 15:43:14 +0000 (11:43 -0400)
committerHui Cao (huica) <huica@cisco.com>
Wed, 2 Nov 2016 15:43:14 +0000 (11:43 -0400)
Squashed commit of the following:

commit 4d37633587be6fa260a82741062e911ed9c219b2
Author: davis mcpherson <davmcphe.cisco.com>
Date:   Tue Nov 1 17:14:36 2016 -0400

    create standalone structs for client and server detector state information

commit 50f73fe4a2db39a857cce8720194399d9c5663a7
Author: davis mcpherson <davmcphe.cisco.com>
Date:   Tue Nov 1 13:01:26 2016 -0400

    restore lua api string names for functions that were unintentially changed during refactoring

commit 71f4f995442b8d99d1daf15c7b735801c89b7f2d
Author: davis mcpherson <davmcphe.cisco.com>
Date:   Fri Oct 28 15:56:05 2016 -0400

    lua detectors must be reloaded when there is a config reload.  this patch adds support so the currently loaded lua detectors remain valid until the appid Inspector they belong to is deleted.  The appid Inspector create for the new config will create its own instance of the LuaDetectorManager and load its set of lua detectors.  some miscellaneous improvements to function prototypes and the procedure for loading the lua detectors are also in this commit

commit b0581f1470eddad797f9a059ef07ba9bfeef3168
Author: davis mcpherson <davmcphe.cisco.com>
Date:   Fri Oct 28 11:50:54 2016 -0400

    rename functions to conform to coding style, move functions only referenced from 1 file static in the file that uses them

commit 481e0b4fd8ce53d45734f392b5f2db6c1203b15a
Author: davis mcpherson <davmcphe.cisco.com>
Date:   Thu Oct 27 10:01:40 2016 -0400

    load lua detectors with luaL_loadfile

33 files changed:
src/network_inspectors/appid/appid_inspector.cc
src/network_inspectors/appid/appid_inspector.h
src/network_inspectors/appid/appid_stats.cc
src/network_inspectors/appid/appid_stats.h
src/network_inspectors/appid/client_plugins/client_app_api.h
src/network_inspectors/appid/client_plugins/client_app_base.cc
src/network_inspectors/appid/client_plugins/client_app_base.h
src/network_inspectors/appid/client_plugins/client_app_bit.cc
src/network_inspectors/appid/client_plugins/client_app_bit_tracker.cc
src/network_inspectors/appid/client_plugins/client_app_msn.cc
src/network_inspectors/appid/client_plugins/client_app_rtp.cc
src/network_inspectors/appid/client_plugins/client_app_ssh.cc
src/network_inspectors/appid/client_plugins/client_app_timbuktu.cc
src/network_inspectors/appid/client_plugins/client_app_tns.cc
src/network_inspectors/appid/client_plugins/client_app_vnc.cc
src/network_inspectors/appid/client_plugins/client_app_ym.cc
src/network_inspectors/appid/detector_plugins/detector_http.cc
src/network_inspectors/appid/detector_plugins/detector_imap.cc
src/network_inspectors/appid/detector_plugins/detector_kerberos.cc
src/network_inspectors/appid/detector_plugins/detector_pattern.cc
src/network_inspectors/appid/detector_plugins/detector_pop3.cc
src/network_inspectors/appid/detector_plugins/detector_sip.cc
src/network_inspectors/appid/detector_plugins/detector_smtp.cc
src/network_inspectors/appid/lua_detector_api.cc
src/network_inspectors/appid/lua_detector_api.h
src/network_inspectors/appid/lua_detector_flow_api.cc
src/network_inspectors/appid/lua_detector_flow_api.h
src/network_inspectors/appid/lua_detector_module.cc
src/network_inspectors/appid/lua_detector_module.h
src/network_inspectors/appid/service_plugins/service_api.h
src/network_inspectors/appid/service_plugins/service_base.cc
src/network_inspectors/appid/service_plugins/service_base.h
src/network_inspectors/appid/service_plugins/service_rpc.cc

index 18ce2366c8c5085a77d12b2940ea3c5d9ca16721..8cab9c50d3ff55b1543dc777a5b873b504ff6622 100644 (file)
@@ -45,8 +45,6 @@
 #include "detector_plugins/detector_pattern.h"
 #include "appid_http_event_handler.h"
 
-THREAD_LOCAL LuaDetectorManager* lua_detector_mgr;
-
 static void dump_appid_stats()
 {
     LogMessage("Application Identification Preprocessor:\n");
@@ -112,25 +110,16 @@ void AppIdInspector::show(SnortConfig*)
 
 void AppIdInspector::tinit()
 {
-    init_appid_statistics(config);
+    init_appid_statistics(*config);
     hostPortAppCacheInit();
     init_appid_forecast();
     init_http_detector();
     init_service_plugins();
     init_client_plugins();
     init_detector_plugins();
-    init_CHP_glossary();
+    init_chp_glossary();
     init_length_app_cache();
-
-    lua_detector_mgr = new LuaDetectorManager;
-    lua_detector_mgr->load_lua_detectors(active_config);
-    lua_detector_mgr->activate_lua_detectors();
-    if(config->debug && list_lua_detectors)
-    {
-        lua_detector_mgr->list_lua_detectors();
-        list_lua_detectors = false;
-    }
-
+    LuaDetectorManager::initialize(*active_config);
     finalize_service_port_patterns();
     finalize_client_port_patterns();
     finalize_service_patterns();
@@ -155,11 +144,11 @@ void AppIdInspector::tterm()
     clean_service_plugins();
     clean_client_plugins();
     clean_http_detector();
-    free_CHP_glossary();
+    free_chp_glossary();
     free_length_app_cache();
 
     AppIdSession::release_free_list_flow_data();
-    delete lua_detector_mgr;
+    LuaDetectorManager::terminate();
     clean_service_state();
 }
 
index a94e7b58d58d7e44f99b33dc3a2fc35243c207b4..ff2d27936fb40381095c259900679725ad7e27ec 100644 (file)
@@ -49,7 +49,6 @@ public:
 private:
     const AppIdModuleConfig* config = nullptr;
     AppIdConfig* active_config = nullptr;
-    bool list_lua_detectors = true;
 };
 
 void httpHeaderCallback(Packet*, HttpParsedHeaders* const);
index 5a090b21eddc1381089b14d1309640aa61afad73..e644fc0fcf6d3a91c3f09bbd74a6c91f77885ac8 100644 (file)
@@ -235,17 +235,17 @@ void update_appid_statistics(AppIdSession* asd)
     }
 }
 
-void init_appid_statistics(const AppIdModuleConfig* config)
+void init_appid_statistics(const AppIdModuleConfig& config)
 {
-    if (config->stats_logging_enabled)
+    if (config.stats_logging_enabled)
     {
         enableAppStats = true;
         std::string stats_file;
         appid_stats_filename = snort_strdup(get_instance_file(stats_file, appid_stats_file_suffix));
 
-        rollPeriod = config->app_stats_rollover_time;
-        rollSize = config->app_stats_rollover_size;
-        bucketInterval = config->app_stats_period;
+        rollPeriod = config.app_stats_rollover_time;
+        rollSize = config.app_stats_rollover_size;
+        bucketInterval = config.app_stats_period;
 
         time_t now = get_time();
         start_stats_period(now);
index 103145f9920d2a5dfef23ae98161a3add13ab80d..8246bae1250c313b6e21b023b23dad0e1c7dd744 100644 (file)
@@ -26,7 +26,7 @@ class AppIdSession;
 class AppIdModuleConfig;
 
 void update_appid_statistics(AppIdSession*);
-void init_appid_statistics(const AppIdModuleConfig* config);
+void init_appid_statistics(const AppIdModuleConfig& config);
 void flush_appid_statistics();
 void cleanup_appid_statistics();
 #endif
index e09c4999757559aa005696cf61babccc02a33234..b7c55c7c19bc814021063318b8039a611c52c723 100644 (file)
@@ -29,7 +29,7 @@
 #include "utils/util.h"
 
 struct Packet;
-struct Detector;
+class Detector;
 
 // Forward declaration for AppId config. Cannot include appIdConfig.h because of
 // circular dependency
index 22c9f8191e252b96c2548414c378d3220a252334..db8ce1e20d850a8760719ef914b3e92aaec00047 100644 (file)
@@ -79,7 +79,7 @@ static const ClientAppApi client_app_api =
 static void CClientAppRegisterPattern(RNAClientAppFCN fcn, IpProtocol proto,
     const uint8_t* const pattern, unsigned size, int position);
 static void LuaClientAppRegisterPattern(RNAClientAppFCN fcn, IpProtocol proto,
-    const uint8_t* const pattern, unsigned size, int position, struct Detector* userData);
+    const uint8_t* const pattern, unsigned size, int position, Detector* userData);
 static void CClientAppRegisterPatternNoCase(RNAClientAppFCN fcn, IpProtocol proto,
     const uint8_t* const pattern, unsigned size, int position);
 static void appSetClientValidator(RNAClientAppFCN fcn, AppId appId, unsigned extractsInfo);
@@ -188,7 +188,7 @@ RNAClientAppModuleConfig* getClientAppModuleConfig(const char* moduleName)
     return mod_config;
 }
 
-const RNAClientAppModule* ClientAppGetClientAppModule(RNAClientAppFCN fcn, struct Detector* userdata)
+const RNAClientAppModule* ClientAppGetClientAppModule(RNAClientAppFCN fcn, Detector* userdata)
 {
     RNAClientAppRecord* li;
 
@@ -261,13 +261,13 @@ static void CClientAppRegisterPatternNoCase(RNAClientAppFCN fcn, IpProtocol prot
 }
 
 static void LuaClientAppRegisterPattern(RNAClientAppFCN fcn, IpProtocol proto,
-    const uint8_t* const pattern, unsigned size, int position, struct Detector* userData)
+    const uint8_t* const pattern, unsigned size, int position, Detector* userData)
 {
     ClientAppRegisterPattern(fcn, proto, pattern, size, position, 0, userData);
 }
 
 void ClientAppRegisterPattern(RNAClientAppFCN fcn, IpProtocol proto, const uint8_t* const pattern,
-    unsigned size, int position, unsigned nocase, struct Detector* userData)
+    unsigned size, int position, unsigned nocase, Detector* userData)
 {
     RNAClientAppRecord* list;
     RNAClientAppRecord* li;
index 5d163b2703f1401445e6f84e3863541f7335b4fc..3b74b8339549046334a3539688fb358f0badd499 100644 (file)
@@ -29,7 +29,7 @@
 
 class AppIdSession;
 class AppIdConfig;
-struct Detector;
+class Detector;
 struct RNAClientAppModule;
 struct Packet;
 struct ClientAppApi;
index aa6ebf9108c0ffc676ec7a0b28ec58d6fbb45539..8ddd508a3861499885baf99f73738ff0308249cb 100644 (file)
@@ -73,7 +73,7 @@ THREAD_LOCAL BIT_CLIENT_APP_CONFIG bit_config;
 
 static CLIENT_APP_RETCODE bit_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE bit_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule bit_client_mod =
 {
@@ -154,7 +154,7 @@ static CLIENT_APP_RETCODE bit_init(const InitClientAppAPI* const init_api, SF_LI
 }
 
 static CLIENT_APP_RETCODE bit_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientBITData* fd;
     uint16_t offset;
index 63e7db63bc1683aa904ea851817e1500ad96efef..ce178600d74d4c1885ee1d91d35223cfea8c8697 100644 (file)
@@ -72,7 +72,7 @@ THREAD_LOCAL BIT_CLIENT_APP_CONFIG udp_bit_config;
 
 static CLIENT_APP_RETCODE udp_bit_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE udp_bit_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule bit_tracker_client_mod =
 {
@@ -156,7 +156,7 @@ static CLIENT_APP_RETCODE udp_bit_init(const InitClientAppAPI* const init_api, S
 }
 
 static CLIENT_APP_RETCODE udp_bit_validate(const uint8_t* data, uint16_t size, const int /*dir*/,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientBITData* fd;
     uint16_t offset;
index 9f4bebd747758ebbf847b70b080831f42d483899..63e99f8499542477a65fdb968f695fde7c5d9332 100644 (file)
@@ -35,7 +35,7 @@ struct MSN_CLIENT_APP_CONFIG
 THREAD_LOCAL MSN_CLIENT_APP_CONFIG msn_config;
 
 static CLIENT_APP_RETCODE msn_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 struct Client_App_Pattern
 {
@@ -114,7 +114,7 @@ static CLIENT_APP_RETCODE msn_init(const InitClientAppAPI* const init_api, SF_LI
 }
 
 static CLIENT_APP_RETCODE msn_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector*)
+    AppIdSession* asd, Packet* pkt, Detector*)
 {
     const uint8_t* end;
     uint8_t version[MAX_VERSION_SIZE];
index 1e403a7e5521d7a276ad153a8ee63dd7b293b840..f831733c31bd08a1238b95ce82ec263bcb430e6a 100644 (file)
@@ -84,7 +84,7 @@ THREAD_LOCAL RTP_CLIENT_APP_CONFIG rtp_config;
 
 static CLIENT_APP_RETCODE rtp_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE rtp_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule rtp_client_mod =
 {
@@ -277,7 +277,7 @@ static CLIENT_APP_RETCODE rtp_init(const InitClientAppAPI* const init_api, SF_LI
 }
 
 static CLIENT_APP_RETCODE rtp_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientRTPData* fd;
     ClientRTPMsg* hdr;
index 27ac8cc3787a2b89cd81bf9db7629170b0302967..a2cd2ca1c9641260351ccb3c4d50117905e67e4a 100644 (file)
@@ -155,7 +155,7 @@ THREAD_LOCAL SSH_CLIENT_CONFIG ssh_client_config;
 
 static CLIENT_APP_RETCODE ssh_client_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE ssh_client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd,  Packet* pkt, struct Detector* userData);
+    AppIdSession* asd,  Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule ssh_client_mod =
 {
@@ -613,7 +613,7 @@ static inline CLIENT_APP_RETCODE ssh_client_sm(const uint8_t* data, uint16_t siz
 }
 
 static CLIENT_APP_RETCODE ssh_client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientSSHData* fd;
     CLIENT_APP_RETCODE sm_ret;
index 8e91368d5bc4ee567a663bfe9f3c806a77b1de0b..1ab22f7d0dce7c7275f41c045c0a1db72cf1b4a1 100644 (file)
@@ -70,7 +70,7 @@ THREAD_LOCAL TIMBUKTU_CLIENT_APP_CONFIG timbuktu_config;
 
 static CLIENT_APP_RETCODE timbuktu_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE timbuktu_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule timbuktu_client_mod =
 {
@@ -152,7 +152,7 @@ static CLIENT_APP_RETCODE timbuktu_init(const InitClientAppAPI* const init_api,
 }
 
 static CLIENT_APP_RETCODE timbuktu_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientTIMBUKTUData* fd;
     uint16_t offset;
index bef4e86671a1d166ee908359c58bc78b37e68a1c..17a4092d7fe3727a0a8d0cb0a2bafa0ba76de1b8 100644 (file)
@@ -131,7 +131,7 @@ THREAD_LOCAL TNS_CLIENT_APP_CONFIG tns_config;
 
 static CLIENT_APP_RETCODE tns_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE tns_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule tns_client_mod =
 {
@@ -214,7 +214,7 @@ static CLIENT_APP_RETCODE tns_init(const InitClientAppAPI* const init_api, SF_LI
 
 #define TNS_MAX_INFO_SIZE    63
 static CLIENT_APP_RETCODE tns_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     char username[TNS_MAX_INFO_SIZE+1];
     ClientTNSData* fd;
index fc6c9605c18abcdda65407532cac5bee0e358fe6..2abe2d78b0b59d6912c8d2778a7d617c0efb7197 100644 (file)
@@ -57,7 +57,7 @@ THREAD_LOCAL VNC_CLIENT_APP_CONFIG vnc_config;
 
 static CLIENT_APP_RETCODE vnc_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE vnc_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 SO_PUBLIC RNAClientAppModule vnc_client_mod =
 {
@@ -141,7 +141,7 @@ static CLIENT_APP_RETCODE vnc_init(const InitClientAppAPI* const init_api, SF_LI
 }
 
 static CLIENT_APP_RETCODE vnc_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientVNCData* fd;
     uint16_t offset;
index bde086cb6ca51d16c099733a19890c1f8f1a4632..1bf34eb7324d7ae303059cc4686fd3248d4ec682 100644 (file)
@@ -41,7 +41,7 @@ THREAD_LOCAL YM_CLIENT_APP_CONFIG ym_config;
 
 static CLIENT_APP_RETCODE ym_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE ym_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 RNAClientAppModule ym_client_mod =
 {
index be97f20bee065b0d30066dc8bcda0fcaaf235f67..a95ccb3be864b4ad43b4cdd0c56e47ebcf903d34 100644 (file)
@@ -2532,7 +2532,7 @@ bool is_webdav_found(HeaderMatchedPatterns* hmp)
 
 static CLIENT_APP_RETCODE http_client_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE http_client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 static int http_service_init(const InitServiceAPI* const init_api);
 static int http_service_validate(ServiceValidationArgs* args);
 
@@ -2640,7 +2640,7 @@ static CLIENT_APP_RETCODE http_client_init(const InitClientAppAPI* const init_ap
 }
 
 static CLIENT_APP_RETCODE http_client_validate(const uint8_t*, uint16_t, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector*)
+    AppIdSession* asd, Packet* pkt, Detector*)
 {
     http_client_mod.api->add_app(asd, APP_ID_HTTP, APP_ID_HTTP + GENERIC_APP_OFFSET, nullptr);
     asd->rna_client_state = RNA_STATE_FINISHED;
index 0db712f4a8d50d7305092b2260565fad6d467591..e5dff198a2d63c33bf141db6b55e8d9d1cbc8ae0 100644 (file)
@@ -667,7 +667,7 @@ static int imap_server_validate(DetectorData* dd, const uint8_t* data, uint16_t
 }
 
 static CLIENT_APP_RETCODE validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     const uint8_t* s = data;
     const uint8_t* end = (data + size);
index c52c0226dcb6a67a8103959402227f6ee6fcaa3e..49853ea04e97aaaa0e81109ebcf55e054a650c93 100644 (file)
@@ -112,7 +112,7 @@ static KRB_CLIENT_APP_CONFIG krb_client_config;
 
 static CLIENT_APP_RETCODE krb_client_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE krb_client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 static RNAClientAppModule client_app_mod =
 {
@@ -955,7 +955,7 @@ static KRB_RETCODE krb_walk_server_packet(KRBState* krbs, const uint8_t* s, cons
 }
 
 static CLIENT_APP_RETCODE krb_client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector*)
+    AppIdSession* asd, Packet* pkt, Detector*)
 {
     const uint8_t* s = data;
     const uint8_t* end = (data + size);
index a3f15ba128e133d9eb9b557e83acb0255ae30792..2b621dacbeeaacee9b0fa271296f2e26fb4045fb 100644 (file)
@@ -39,7 +39,7 @@ static void pattern_service_clean();
 static CLIENT_APP_RETCODE client_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE client_init_tcp(const InitClientAppAPI* const init_api, SF_LIST* config);
 static CLIENT_APP_RETCODE client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 static void client_clean();
 static const InitServiceAPI* iniServiceApi;
 static const InitClientAppAPI* iniClientApi;
@@ -778,7 +778,7 @@ static void client_clean()
 }
 
 static CLIENT_APP_RETCODE client_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector*)
+    AppIdSession* asd, Packet* pkt, Detector*)
 {
     AppId id;
     const RNAServiceElement* service = nullptr;
index 60bb00a8f9ccbbc8d8bce120fdb0becb14fc93f9..7b01aace66e726c51fe05e569171ae10be208aaf 100644 (file)
@@ -61,7 +61,7 @@ static POP3_CLIENT_APP_CONFIG pop3_config;
 static CLIENT_APP_RETCODE pop3_ca_init(const InitClientAppAPI* const init_api, SF_LIST* config);
 static void pop3_ca_clean();
 static CLIENT_APP_RETCODE pop3_ca_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 static RNAClientAppModule client_app_mod =
 {
@@ -662,7 +662,7 @@ ven_ver_done:;
 }
 
 static CLIENT_APP_RETCODE pop3_ca_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     const uint8_t* s = data;
     const uint8_t* end = (data + size);
index bfc494267dfe61503bfd6645716aa9e62599efdb..4fb0ff5fb68a278b2922783b8af1621cd2f580dc 100644 (file)
@@ -310,7 +310,7 @@ static void clientDataFree(void* data)
 
 // static const char* const SIP_USRNAME_BEGIN_MARKER = "<sip:";
 static CLIENT_APP_RETCODE sip_client_validate(const uint8_t*, uint16_t, const int,
-    AppIdSession* asd, Packet*, struct Detector*)
+    AppIdSession* asd, Packet*, Detector*)
 {
     ClientSIPData* fd;
 
@@ -329,7 +329,7 @@ static CLIENT_APP_RETCODE sip_client_validate(const uint8_t*, uint16_t, const in
 }
 
 static CLIENT_APP_RETCODE sip_tcp_client_validate(const uint8_t* data, uint16_t size, const int
-    dir, AppIdSession* asd, Packet* pkt, struct Detector* userData)
+    dir, AppIdSession* asd, Packet* pkt, Detector* userData)
 {
     return sip_client_validate(data, size, dir, asd, pkt, userData);
 }
index 7db16eb82e80098a97dc2863dc7d936f40b5bcfd..10add1c008fc7242e0c19b16e5f452e8c040c319 100644 (file)
@@ -93,7 +93,7 @@ THREAD_LOCAL SMTP_CLIENT_APP_CONFIG smtp_config;
 
 static CLIENT_APP_RETCODE smtp_ca_init(const InitClientAppAPI* const init_api, SF_LIST *config);
 static CLIENT_APP_RETCODE smtp_ca_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector* userData);
+    AppIdSession* asd, Packet* pkt, Detector* userData);
 
 static RNAClientAppModule  smtp_client_mod =
 {
@@ -576,7 +576,7 @@ static inline SMTPDetectorData* smtp_get_SMTPDetectorData(AppIdSession* asd)
 
 // #define UNIT_TEST_SKIP
 static CLIENT_APP_RETCODE smtp_ca_validate(const uint8_t* data, uint16_t size, const int dir,
-    AppIdSession* asd, Packet* pkt, struct Detector*)
+    AppIdSession* asd, Packet* pkt, Detector*)
 {
     SMTPDetectorData* dd;
     ClientSMTPData* fd;
index 19735ff71c58064730e2f8fdd18589be1b01f84e..51c909b1630f7c6071519a76c7919e32f3a26986 100644 (file)
 #define OVECCOUNT 30    /* should be a multiple of 3 */
 
 #define CHECK_INPUTS() \
-    if ( !checkServiceElement(ud) || !ud->validateParams.pkt ) \
+    if ( !check_service_element(ud) || !ud->validateParams.pkt ) \
     { \
         lua_pushnumber(L, SERVICE_ENULL); \
         return 1; \
     }
 
-enum
+enum LuaLogLevels
 {
     LUA_LOG_CRITICAL = 0,
     LUA_LOG_ERR = 1,
@@ -75,16 +75,16 @@ ProfileStats luaCustomPerfStats;
 
 static THREAD_LOCAL SFXHASH* CHP_glossary = nullptr;      // keep track of http multipatterns here
 
-static int genericDataFree(void* /* key */, void* data)
+static int free_chp_data(void* /* key */, void* data)
 {
     if (data)
         snort_free(data);
     return 0;
 }
 
-int init_CHP_glossary()
+int init_chp_glossary()
 {
-    if (!(CHP_glossary = sfxhash_new(1024, sizeof(AppId), 0, 0, 0, nullptr, &genericDataFree, 0)))
+    if (!(CHP_glossary = sfxhash_new(1024, sizeof(AppId), 0, 0, 0, nullptr, &free_chp_data, 0)))
     {
         ErrorMessage("Config: failed to allocate memory for an sfxhash.");
         return 0;
@@ -93,14 +93,14 @@ int init_CHP_glossary()
         return 1;
 }
 
-void free_CHP_glossary()
+void free_chp_glossary()
 {
     if (CHP_glossary)
         sfxhash_delete(CHP_glossary);
     CHP_glossary = nullptr;
 }
 
-static inline int ConvertStringToAddress(const char* string, sfip_t* address)
+static inline int convert_string_to_address(const char* string, sfip_t* address)
 {
     int af;
     struct in6_addr buf;
@@ -123,30 +123,8 @@ static inline int ConvertStringToAddress(const char* string, sfip_t* address)
     return 1;    // success
 }
 
-// FIXIT-M lifetime of detector is easy to misuse with this idiom
-// Leaves 1 value (the Detector userdata) at the top of the stack
-Detector* createDetector(lua_State* L, const char* detectorName)
-{
-    auto detector = new Detector();
-    detector->myLuaState = L;
-    detector->name = detectorName;
-
-    UserData<Detector>::push(L, DETECTOR, detector);
-
-    // add a lua reference so the detector doesn't get garbage-collected
-    lua_pushvalue(L, -1);
-    detector->detectorUserDataRef = luaL_ref(L, LUA_REGISTRYINDEX);
-    return detector;
-}
-
-// must be called only when RNA is exitting.
-static void freeDetector(Detector* detector)
-{
-       delete detector;
-}
-
 // check service element, Allocate if necessary
-int checkServiceElement(Detector* detector)
+int check_service_element(Detector* detector)
 {
     if ( !detector->server.pServiceElement )
     {
@@ -179,9 +157,9 @@ static int service_init(lua_State* L)
 
     if ( lua_isfunction(L, -1) && lua_isfunction(L, -2) )
     {
-        if ( checkServiceElement(ud) )
+        if ( check_service_element(ud) )
         {
-            ud->server.pServiceElement->validate = validateAnyService;
+            ud->server.pServiceElement->validate = validate_service_application;
             ud->server.pServiceElement->userdata = ud.ptr;
             ud->server.pServiceElement->detectorType = DETECTOR_TYPE_DECODER;
         }
@@ -210,7 +188,7 @@ static int service_init(lua_State* L)
 //  #4 - size/stack - number of bytes in pattern
 //  #5 - position/stack -  position offset where to start matching pattern.
 //  return - status/stack - 0 if successful, -1 otherwise.
-static int service_registerPattern(lua_State* L)
+static int service_register_pattern(lua_State* L)
 {
     int index = 1;
 
@@ -236,15 +214,15 @@ static int service_registerPattern(lua_State* L)
 
     /*mpse library does not hold reference to pattern therefore we dont need to allocate it. */
 
-    ServiceRegisterPatternDetector(validateAnyService, (IpProtocol)protocol, (uint8_t*)pattern,
+    ServiceRegisterPatternDetector(validate_service_application, (IpProtocol)protocol, (uint8_t*)pattern,
         size, position, ud, ud->server.serviceModule.name);
 
     lua_pushnumber(L, 0);
     return 1;
 }
 
-static void appSetLuaClientValidator(RNAClientAppFCN fcn, AppId appId, unsigned extractsInfo,
-        struct Detector* data)
+static void set_lua_client_validator(RNAClientAppFCN fcn, AppId appId, unsigned extractsInfo,
+        Detector* data)
 {
     AppInfoTableEntry* entry;
 
@@ -276,8 +254,8 @@ static void appSetLuaClientValidator(RNAClientAppFCN fcn, AppId appId, unsigned
     }
 }
 
-static void appSetLuaServiceValidator(RNAServiceValidationFCN fcn, AppId appId, unsigned extractsInfo,
-    struct Detector* data)
+static void set_lua_service_validator(RNAServiceValidationFCN fcn, AppId appId, unsigned extractsInfo,
+    Detector* data)
 {
     AppInfoTableEntry* entry;
 
@@ -305,21 +283,20 @@ static void appSetLuaServiceValidator(RNAServiceValidationFCN fcn, AppId appId,
     }
 }
 
-static int common_registerAppId(lua_State* L)
+static int common_register_application_id(lua_State* L)
 {
-    unsigned int appId;
     int index = 1;
 
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
-    appId = lua_tonumber(L, index++);
+    AppId appId = lua_tonumber(L, index++);
 
     if ( !ud->packageInfo.server.initFunctionName.empty() )
-        appSetLuaServiceValidator(validateAnyService, appId, APPINFO_FLAG_SERVICE_ADDITIONAL,
-                ud.ptr);
+        set_lua_service_validator(validate_service_application, appId,
+                                  APPINFO_FLAG_SERVICE_ADDITIONAL, ud.ptr);
 
     if ( !ud->packageInfo.client.initFunctionName.empty() )
-        appSetLuaClientValidator(
-            validateAnyClientApp, appId, APPINFO_FLAG_CLIENT_ADDITIONAL, ud.ptr);
+        set_lua_client_validator(validate_client_application, appId,
+                                 APPINFO_FLAG_CLIENT_ADDITIONAL, ud.ptr);
 
     AppInfoManager::get_instance().set_app_info_active(appId);
 
@@ -327,7 +304,7 @@ static int common_registerAppId(lua_State* L)
     return 1;
 }
 
-static int Detector_htons(lua_State* L)
+static int detector_htons(lua_State* L)
 {
     unsigned short aShort = lua_tonumber(L, 2);
 
@@ -335,7 +312,7 @@ static int Detector_htons(lua_State* L)
     return 1;
 }
 
-static int Detector_htonl(lua_State* L)
+static int detector_htonl(lua_State* L)
 {
     unsigned int anInt = lua_tonumber(L, 2);
 
@@ -349,7 +326,7 @@ static int Detector_htonl(lua_State* L)
 // lua params:
 //  #1 - level - level of message. See DetectorCommon for enumeration.
 //  #2 - message - message to be logged.
-static int Detector_logMessage(lua_State* L)
+static int detector_log_message(lua_State* L)
 {
     const auto& name = (*UserData<Detector>::check(L, DETECTOR, 1))->server.serviceModule.name;
 
@@ -389,7 +366,7 @@ static int Detector_logMessage(lua_State* L)
 //  2 - major/stack - major number of application
 //  3 - minor/stack - minor number of application
 //  4 - flags/stack - any flags
-static int service_analyzePayload(lua_State* L)
+static int service_analyze_payload(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
     unsigned int payloadId = lua_tonumber(L, 2);
@@ -410,13 +387,11 @@ static int service_analyzePayload(lua_State* L)
 // Right now there is only one detector so there is a one-to-one mapping, but the framework
 // will have to support multiple detectors in production environment. Core engine API will be
 // changed to take an additional void* that will be used to call only a unique detector.
-int validateAnyService(ServiceValidationArgs* args)
+int validate_service_application(ServiceValidationArgs* args)
 {
     Profile lua_detector_context(luaCustomPerfStats);
 
-    int retValue;
     auto detector = args->userdata;
-
     if ( !detector )
     {
         ErrorMessage("The service validation arguments do not contain a detector object\n");
@@ -424,13 +399,11 @@ int validateAnyService(ServiceValidationArgs* args)
     }
 
     auto L = detector->myLuaState;
-
     detector->validateParams.data = args->data;
     detector->validateParams.size = args->size;
     detector->validateParams.dir = args->dir;
     detector->validateParams.asd = args->asd;
     detector->validateParams.pkt = args->pkt;
-
     const auto& serverName = detector->name;
 
     /*Note: Some frequently used header fields may be extracted and stored in detector for
@@ -462,7 +435,7 @@ int validateAnyService(ServiceValidationArgs* args)
     }
 
     /**detectorFlows must be destroyed after each packet is processed.*/
-    sflist_static_free_all(&allocatedFlowList, freeDetectorFlow);
+    LuaDetectorManager::free_detector_flows();
 
     /* retrieve result */
     if ( !lua_isnumber(L, -1) )
@@ -472,13 +445,10 @@ int validateAnyService(ServiceValidationArgs* args)
         return SERVICE_ENULL;
     }
 
-    retValue = lua_tonumber(L, -1);
-    lua_pop(L, 1);  /* pop returned value */
-
+    int retValue = lua_tonumber(L, -1);
+    lua_pop(L, 1);
     DebugFormat(DEBUG_APPID, "server %s: Validator returned %d\n", serverName.c_str(), retValue);
-
     detector->validateParams.pkt = nullptr;
-
     return retValue;
 }
 
@@ -491,7 +461,7 @@ int validateAnyService(ServiceValidationArgs* args)
 // get get a service Id (an integer) from database.
 // @param serviceName/stack - Name of service
 // @return serviceId/stack - serviceId if successful, -1 otherwise.
-static int service_getServiceId(lua_State* L)
+static int service_get_service_id(lua_State* L)
 {
     auto ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -504,7 +474,7 @@ static int service_getServiceId(lua_State* L)
 // @param protocol/stack - protocol type. Values can be {tcp=6, udp=17 }
 // @param port/stack - port number to register.
 // @return status/stack - 0 if successful, -1 otherwise.
-static int service_addPorts(lua_State* L)
+static int service_add_ports(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -512,7 +482,7 @@ static int service_addPorts(lua_State* L)
     pp.proto = (IpProtocol)lua_tonumber(L, 2);
     pp.port = lua_tonumber(L, 3);
     pp.reversed_validation = lua_tonumber(L, 5);
-    pp.validate = &validateAnyService;
+    pp.validate = &validate_service_application;
 
     if ( ((pp.proto != IpProtocol::UDP) && (pp.proto != IpProtocol::TCP)) || !pp.port )
     {
@@ -527,7 +497,6 @@ static int service_addPorts(lua_State* L)
     }
 
     ++ud->server.pServiceElement->ref_count;
-
     lua_pushnumber(L, 0);
     return 1;
 }
@@ -535,28 +504,21 @@ static int service_addPorts(lua_State* L)
 // Remove all ports for a given service. Lua detectors call this function to remove ports for this
 // service when exiting. This function is not used currently by any detectors.
 // @return status/stack - 0 if successful, -1 otherwise.
-static int service_removePorts(lua_State* L)
+static int service_remove_ports(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    detectorRemoveAllPorts(ud);
-
+    ServiceRemovePorts(&validate_service_application, ud);
     lua_pushnumber(L, 0);
     return 1;
 }
 
-// Shared function between Lua API and RNA core.
-void detectorRemoveAllPorts(Detector* detector)
-{
-    ServiceRemovePorts(&validateAnyService, detector);
-}
-
 // Set service name. Lua detectors call this function to set service name. It is preferred to set
 // service name
 // when a detector is created. Afterwards there is rarely a need to change service name.
 // @param serviceName/stack - Name of service
 // @return status/stack - 0 if successful, -1 otherwise.
-static int service_setServiceName(lua_State* L)
+static int service_set_service_name(lua_State* L)
 {
     lua_pushnumber(L, 0);
     return 1;
@@ -570,7 +532,7 @@ static int service_setServiceName(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return serviceName/stack - service name if successful, nil otherwise.
  */
-static int service_getServiceName(lua_State* L)
+static int service_get_service_name(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -586,7 +548,7 @@ static int service_getServiceName(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return integer/stack - -1 if failed, 0 if sourcefire created, 1 otherwise.
  */
-static int service_isCustomDetector(lua_State* L)
+static int service_is_custom_detector(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
     lua_pushnumber(L, ud->isCustom);
@@ -602,7 +564,7 @@ static int service_isCustomDetector(lua_State* L)
  * @param validatorName/stack - Name of service validator
  * @return int - Number of elements on stack, which is always 0.
  */
-static int service_setValidator(lua_State* L)
+static int service_set_validator(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -620,9 +582,7 @@ static int service_setValidator(lua_State* L)
     }
 
     lua_pop(L, 1);
-
     ud->packageInfo.server.validateFunctionName = pValidator;
-
     lua_pushnumber(L, 0);
     return 1;
 }
@@ -635,21 +595,20 @@ static int service_setValidator(lua_State* L)
  * @param sourcePort/stack - Source port number.
  * @return int - Number of elements on stack, which is always 0.
  */
-static int service_addDataId(lua_State* L)
+static int service_add_data_id(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
     uint16_t sport = lua_tonumber(L, 2);
 
     /*check inputs and whether this function is called in context of a
       packet */
-    if ( !checkServiceElement(ud) || !ud->validateParams.pkt )
+    if ( !check_service_element(ud) || !ud->validateParams.pkt )
     {
         lua_pushnumber(L, -1);
         return 1;
     }
 
     ud->validateParams.asd->add_flow_data_id(sport, ud->server.pServiceElement);
-
     lua_pushnumber(L, 0);
     return 1;
 }
@@ -664,21 +623,17 @@ static int service_addDataId(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return int/stack - values from enum SERVICE_RETCODE
  */
-static int service_addService(
-    lua_State* L
-    )
+static int service_add_service(lua_State* L)
 {
-    char* vendor, * version;
-    unsigned int serviceId, retValue = SERVICE_ENULL;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    serviceId = lua_tonumber(L, 2);
-    vendor = (char*)luaL_optstring(L, 3, nullptr);
-    version = (char*)luaL_optstring(L, 4, nullptr);
+    AppId serviceId = lua_tonumber(L, 2);
+    char* vendor = (char*)luaL_optstring(L, 3, nullptr);
+    char* version = (char*)luaL_optstring(L, 4, nullptr);
 
     /*check inputs (vendor and version may be null) and whether this function is
       called in context of a packet */
-    if ( !checkServiceElement(ud) || !ud->validateParams.pkt )
+    if ( !check_service_element(ud) || !ud->validateParams.pkt )
     {
         lua_pushnumber(L, SERVICE_ENULL);
         return 1;
@@ -687,9 +642,10 @@ static int service_addService(
     /*Phase2 - discuss RNAServiceSubtype will be maintained on lua side therefore the last
       parameter on the following call is nullptr.
       Subtype is not displayed on DC at present. */
-    retValue = AppIdServiceAddService(ud->validateParams.asd, ud->validateParams.pkt,
+    unsigned int retValue = AppIdServiceAddService(ud->validateParams.asd, ud->validateParams.pkt,
         ud->validateParams.dir, ud->server.pServiceElement,
-        AppInfoManager::get_instance().get_appid_by_service_id(serviceId), vendor, version, nullptr);
+        AppInfoManager::get_instance().get_appid_by_service_id(serviceId),
+        vendor, version, nullptr);
 
     lua_pushnumber(L, retValue);
     return 1;
@@ -702,10 +658,9 @@ static int service_addService(
  * @return int - Number of elements on stack, which is always 1.
  * @return int/stack - values from enum SERVICE_RETCODE
  */
-static int service_failService(lua_State* L)
+static int service_fail_service(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
-
     CHECK_INPUTS();
 
     unsigned int retValue = AppIdServiceFailService(ud->validateParams.asd,
@@ -723,10 +678,9 @@ static int service_failService(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return int/stack - values from enum SERVICE_RETCODE
  */
-static int service_inProcessService(lua_State* L)
+static int service_in_process_service(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
-
     CHECK_INPUTS();
 
     unsigned int retValue = AppIdServiceInProcess(ud->validateParams.asd, ud->validateParams.pkt,
@@ -743,14 +697,12 @@ static int service_inProcessService(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return int/stack - values from enum SERVICE_RETCODE
  */
-static int service_inCompatibleData(lua_State* L)
+static int service_set_incompatible_data(lua_State* L)
 {
-    unsigned int retValue = SERVICE_ENULL;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
-
     CHECK_INPUTS();
 
-    retValue = AppIdServiceIncompatibleData(ud->validateParams.asd,
+    unsigned int retValue = AppIdServiceIncompatibleData(ud->validateParams.asd,
         ud->validateParams.pkt,
         ud->validateParams.dir, ud->server.pServiceElement,
         APPID_SESSION_DATA_NONE, ud->appid_config);
@@ -768,9 +720,7 @@ static int service_inCompatibleData(lua_State* L)
  * @return int - Number of elements on stack, which is always 1 if successful, 0 otherwise.
  * @return packetSize/stack - size of packet on stack, if successful.
  */
-static int Detector_getPacketSize(
-    lua_State* L
-    )
+static int detector_get_packet_size(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -786,9 +736,7 @@ static int Detector_getPacketSize(
  * @return int - Number of elements on stack, which is always 1 if successful, 0 otherwise.
  * @return packetDir/stack - direction of packet on stack, if successful.
  */
-static int Detector_getPacketDir(
-    lua_State* L
-    )
+static int detector_get_packet_direction(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -805,79 +753,65 @@ static int Detector_getPacketDir(
  * @return matchedStrings/stack - matched strings are pushed on stack starting with group 0.
  *     There may be 0 or more strings.
  */
-static int Detector_getPcreGroups(
-    lua_State* L
-    )
+static int detector_get_pcre_groups(lua_State* L)
 {
-    char* pattern;
-    unsigned int offset;
-    pcre* re;
     int ovector[OVECCOUNT];
     const char* error;
     int erroffset;
-    int rc, i;
+
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
+    char* pattern = (char*)lua_tostring(L, 2);
+    unsigned int offset = lua_tonumber(L, 3);     /*offset can be zero, no check necessary. */
 
-    pattern = (char*)lua_tostring(L, 2);
-    offset = lua_tonumber(L, 3);     /*offset can be zero, no check necessary. */
+    /*compile the regular expression pattern, and handle errors */
+    pcre* re = pcre_compile(pattern,              /*the pattern */
+                      PCRE_DOTALL,          /*default options - dot matches everything including newline */
+                      &error,               /*for error message */
+                      &erroffset,           /*for error offset */
+                      nullptr);             /*use default character tables */
 
+    if (re == nullptr)
     {
-        /*compile the regular expression pattern, and handle errors */
-        re = pcre_compile(
-            pattern,              /*the pattern */
-            PCRE_DOTALL,          /*default options - dot matches everything including newline */
-            &error,               /*for error message */
-            &erroffset,           /*for error offset */
-            nullptr);                /*use default character tables */
-
-        if (re == nullptr)
-        {
-            ErrorMessage("PCRE compilation failed at offset %d: %s\n", erroffset, error);
-            return 0;
-        }
-
-        /*pattern match against the subject string. */
-        rc = pcre_exec(
-            re,                                         /*compiled pattern */
-            nullptr,                                       /*no extra data */
-            (char*)ud->validateParams.data,       /*subject string */
-            ud->validateParams.size,              /*length of the subject */
-            offset,                                     /*offset 0 */
-            0,                                          /*default options */
-            ovector,                                    /*output vector for substring information
-                                                           */
-            OVECCOUNT);                                 /*number of elements in the output vector
-                                                           */
-
-        if (rc < 0)
-        {
-            /*Matching failed: clubbing PCRE_ERROR_NOMATCH with other errors. */
-            pcre_free(re);
-            return 0;
-        }
+        ErrorMessage("PCRE compilation failed at offset %d: %s\n", erroffset, error);
+        return 0;
+    }
 
-        /*Match succeded */
+    /*pattern match against the subject string. */
+    int rc = pcre_exec(re,                                 // compiled pattern
+                       nullptr,                            // no extra data
+                       (char*)ud->validateParams.data,     // subject string
+                       ud->validateParams.size,            // length of the subject
+                       offset,                             // offset 0
+                       0,                                  // default options
+                       ovector,                            // output vector for substring information
+                       OVECCOUNT);                         // number of elements in the output vector
 
-        /*printf("\nMatch succeeded at offset %d", ovector[0]); */
-        pcre_free(re);
 
+    if( rc >= 0 )
+    {
         if (rc == 0)
         {
             /*overflow of matches */
-            rc = OVECCOUNT/3;
-            /*printf("ovector only has room for %d captured substrings", rc - 1); */
-            ErrorMessage("ovector only has room for %d captured substrings\n",rc - 1);
+            rc = OVECCOUNT / 3;
+            WarningMessage("ovector only has room for %d captured substrings\n", rc - 1);
         }
-    }
 
-    lua_checkstack (L, rc);
-    for (i = 0; i < rc; i++)
+        lua_checkstack(L, rc);
+        for (int i = 0; i < rc; i++)
+        {
+            lua_pushlstring(L, (char*)ud->validateParams.data + ovector[2*i], ovector[2*i+1] -
+                            ovector[2*i]);
+        }
+    }
+    else
     {
-        /*printf("%2d: %.*s\n", i, , substring_start); */
-        lua_pushlstring(L, (char*)ud->validateParams.data + ovector[2*i], ovector[2*i+1] -
-            ovector[2*i]);
+        // log errors except no matches
+        if( rc != PCRE_ERROR_NOMATCH)
+            WarningMessage("PCRE regular expression group match failed. rc: %d\n", rc);
+        rc = 0;
     }
 
+    pcre_free(re);
     return rc;
 }
 
@@ -892,22 +826,14 @@ static int Detector_getPcreGroups(
  * @return int - Number of group matches.  May be 1 if successful, and 0 if error is encountered.
  * @return memCmpResult/stack - returns -1,0,1 based on memcmp result.
  */
-static int Detector_memcmp(
-    lua_State* L
-    )
+static int detector_memcmp(lua_State* L)
 {
-    char* pattern;
-    unsigned int patternLen;
-    unsigned int offset;
-    int rc;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    pattern = (char*)lua_tostring(L, 2);
-    patternLen = lua_tonumber(L, 3);
-    offset = lua_tonumber(L, 4);     /*offset can be zero, no check necessary. */
-
-    rc = memcmp((char*)ud->validateParams.data + offset, pattern, patternLen);
-
+    char* pattern = (char*)lua_tostring(L, 2);
+    unsigned int patternLen = lua_tonumber(L, 3);
+    unsigned int offset = lua_tonumber(L, 4);     /*offset can be zero, no check necessary. */
+    int rc = memcmp((char*)ud->validateParams.data + offset, pattern, patternLen);
     lua_checkstack (L, 1);
     lua_pushnumber(L, rc);
     return 1;
@@ -919,10 +845,9 @@ static int Detector_memcmp(
  * @return int - Number of elements on stack, which is protocol type if successful, 0 otherwise.
  * @return protocol type TCP or UDP
  */
-static int Detector_getProtocolType(lua_State* L)
+static int detector_get_protocol_type(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
-
     if ( !ud->validateParams.pkt || !ud->validateParams.pkt->has_ip() )
     {
         // FIXIT-M J why the inconsistent use of checkstack?
@@ -944,72 +869,64 @@ static int Detector_getProtocolType(lua_State* L)
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return IPv4/stack - Source IPv4 addresss.
  */
-static int Detector_getPktSrcIPAddr(lua_State* L)
+static int detector_get_packet_src_addr(lua_State* L)
 {
-    const sfip_t* ipAddr;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_src();
-
+    const sfip_t* ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_src();
     lua_checkstack (L, 1);
     lua_pushnumber(L, ipAddr->ip32[0]);
     return 1;
 }
 
-/**Get source port number from IP header.
+/**Get destination IP address from IP header.
  *
  * @param Lua_State* - Lua state variable.
  * @param detector/stack - detector object
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
- * @return portNumber/stack - source port number.
+ * @return IPv4/stack - destination IPv4 addresss.
  */
-static int Detector_getPktSrcPort(lua_State* L)
+static int detector_get_packet_dst_addr(lua_State* L)
 {
-    unsigned int port;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    port = ud->validateParams.pkt->ptrs.sp;
-
+    const sfip_t* ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_dst();
     lua_checkstack (L, 1);
-    lua_pushnumber(L, port);
+    lua_pushnumber(L, ipAddr->ip32[0]);
     return 1;
 }
 
-/**Get destination port number from IP header.
+/**Get source port number from IP header.
  *
  * @param Lua_State* - Lua state variable.
  * @param detector/stack - detector object
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
- * @return portNumber/stack - destination Port number.
+ * @return portNumber/stack - source port number.
  */
-static int Detector_getPktDstPort(lua_State* L)
+static int detector_get_packet_src_port(lua_State* L)
 {
-    unsigned int port;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    port = ud->validateParams.pkt->ptrs.dp;
-
+    unsigned int port = ud->validateParams.pkt->ptrs.sp;
     lua_checkstack (L, 1);
     lua_pushnumber(L, port);
     return 1;
 }
 
-/**Get destination IP address from IP header.
+/**Get destination port number from IP header.
  *
  * @param Lua_State* - Lua state variable.
  * @param detector/stack - detector object
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
- * @return IPv4/stack - destination IPv4 addresss.
+ * @return portNumber/stack - destination Port number.
  */
-static int Detector_getPktDstIPAddr(lua_State* L)
+static int detector_get_packet_dst_port(lua_State* L)
 {
-    const sfip_t* ipAddr;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    ipAddr = ud->validateParams.pkt->ptrs.ip_api.get_dst();
-
+    unsigned int port = ud->validateParams.pkt->ptrs.dp;
     lua_checkstack (L, 1);
-    lua_pushnumber(L, ipAddr->ip32[0]);
+    lua_pushnumber(L, port);
     return 1;
 }
 
@@ -1021,36 +938,31 @@ static int Detector_getPktDstIPAddr(lua_State* L)
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return packetCount/stack - Total packet processed by RNA.
  */
-static int Detector_getPktCount(lua_State* L)
+static int detector_get_packet_count(lua_State* L)
 {
     lua_checkstack (L, 1);
     lua_pushnumber(L, appid_stats.processed_packets);
     return 1;
 }
 
-CLIENT_APP_RETCODE validateAnyClientApp( const uint8_t* data, uint16_t size, const int dir,
+CLIENT_APP_RETCODE validate_client_application( const uint8_t* data, uint16_t size, const int dir,
     AppIdSession* asd, Packet* pkt, Detector* detector )
 {
     Profile lua_profile_context(luaCustomPerfStats);
 
-    int retValue;
-    lua_State* myLuaState;
-    const char* validateFn;
-    const char* clientName;
-
     if (!data || !asd || !pkt || !detector)
     {
         return CLIENT_APP_ENULL;
     }
 
-    myLuaState = detector->myLuaState;
+    lua_State* myLuaState = detector->myLuaState;
     detector->validateParams.data = data;
     detector->validateParams.size = size;
     detector->validateParams.dir = dir;
     detector->validateParams.asd = asd;
     detector->validateParams.pkt = (Packet*)pkt;
-    validateFn = detector->packageInfo.client.validateFunctionName.c_str();
-    clientName = detector->name.c_str();
+    const char* validateFn = detector->packageInfo.client.validateFunctionName.c_str();
+    const char* clientName = detector->name.c_str();
 
     if ((!validateFn) || !(lua_checkstack(myLuaState, 1)))
     {
@@ -1073,7 +985,7 @@ CLIENT_APP_RETCODE validateAnyClientApp( const uint8_t* data, uint16_t size, con
     }
 
     /**detectorFlows must be destroyed after each packet is processed.*/
-    sflist_static_free_all(&allocatedFlowList, freeDetectorFlow);
+    LuaDetectorManager::free_detector_flows();
 
     /* retrieve result */
     if (!lua_isnumber(myLuaState, -1))
@@ -1082,7 +994,7 @@ CLIENT_APP_RETCODE validateAnyClientApp( const uint8_t* data, uint16_t size, con
         detector->validateParams.pkt = nullptr;
     }
 
-    retValue = lua_tonumber(myLuaState, -1);
+    int retValue = lua_tonumber(myLuaState, -1);
     lua_pop(myLuaState, 1);  /* pop returned value */
     /*lua_settop(myLuaState, 0); */
 
@@ -1093,19 +1005,15 @@ CLIENT_APP_RETCODE validateAnyClientApp( const uint8_t* data, uint16_t size, con
     return (CLIENT_APP_RETCODE)retValue;
 }
 
-static int client_registerPattern(lua_State* L)
+static int client_register_pattern(lua_State* L)
 {
-    IpProtocol protocol;
-    size_t size;
-    const char* pattern;
-    unsigned int position;
     int index = 1;
 
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
-    protocol = (IpProtocol)lua_tonumber(L, index++);
-    pattern = lua_tostring(L, index++);
-    size = lua_tonumber(L, index++);
-    position = lua_tonumber(L, index++);
+    IpProtocol protocol = (IpProtocol)lua_tonumber(L, index++);
+    const char* pattern = lua_tostring(L, index++);
+    size_t size = lua_tonumber(L, index++);
+    unsigned int position = lua_tonumber(L, index++);
 
     /*Note: we can not give callback into lua directly so we have to
       give a local callback function, which will do demuxing and
@@ -1115,7 +1023,7 @@ static int client_registerPattern(lua_State* L)
 
     ud->client.appModule.userData = ud.ptr;
     ClientAppLoadCallback((void*)&(ud->client.appModule));
-    ClientAppRegisterPattern(validateAnyClientApp, protocol, (const uint8_t*)pattern,
+    ClientAppRegisterPattern(validate_client_application, protocol, (const uint8_t*)pattern,
             size, position, 0, ud);
 
     lua_pushnumber(L, 0);
@@ -1140,16 +1048,13 @@ static int client_init(lua_State*)
     return 0;
 }
 
-static int service_addClient(lua_State* L)
+static int service_add_client(lua_State* L)
 {
-    AppId clienAppId, serviceId;
-    const char* version;
-
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    clienAppId = lua_tonumber(L, 2);
-    serviceId = lua_tonumber(L, 3);
-    version = lua_tostring(L, 4);
+    AppId clientAppId = lua_tonumber(L, 2);
+    AppId serviceId = lua_tonumber(L, 3);
+    const char* version = lua_tostring(L, 4);
 
     if ( !ud->validateParams.pkt || !version )
     {
@@ -1157,21 +1062,19 @@ static int service_addClient(lua_State* L)
         return 1;
     }
 
-    AppIdAddClientApp(ud->validateParams.asd, serviceId, clienAppId, version);
+    AppIdAddClientApp(ud->validateParams.asd, serviceId, clientAppId, version);
 
     lua_pushnumber(L, 0);
     return 1;
 }
 
-static int client_addApp(lua_State* L)
+static int client_add_application(lua_State* L)
 {
-    unsigned int serviceId, productId;
-    const char* version;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    serviceId = lua_tonumber(L, 2);
-    productId = lua_tonumber(L, 4);
-    version = lua_tostring(L, 5);
+    unsigned int serviceId = lua_tonumber(L, 2);
+    unsigned int productId = lua_tonumber(L, 4);
+    const char* version = lua_tostring(L, 5);
 
     CHECK_INPUTS();
 
@@ -1189,12 +1092,11 @@ static int client_addApp(lua_State* L)
     return 1;
 }
 
-static int client_addInfo(lua_State* L)
+static int client_add_info(lua_State* L)
 {
-    const char* info;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    info = lua_tostring(L, 2);
+    const char* info = lua_tostring(L, 2);
 
     CHECK_INPUTS();
 
@@ -1210,14 +1112,12 @@ static int client_addInfo(lua_State* L)
     return 1;
 }
 
-static int client_addUser(lua_State* L)
+static int client_add_user(lua_State* L)
 {
-    unsigned int serviceId;
-    const char* userName;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
-    userName = lua_tostring(L, 2);
-    serviceId = lua_tonumber(L, 3);
+    const char* userName = lua_tostring(L, 2);
+    unsigned int serviceId = lua_tonumber(L, 3);
 
     CHECK_INPUTS();
 
@@ -1234,12 +1134,10 @@ static int client_addUser(lua_State* L)
     return 1;
 }
 
-static int client_addPayload(lua_State* L)
+static int client_add_payload(lua_State* L)
 {
-    unsigned int payloadId;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
-
-    payloadId = lua_tonumber(L, 2);
+    unsigned int payloadId = lua_tonumber(L, 2);
 
     CHECK_INPUTS();
 
@@ -1266,7 +1164,7 @@ static int client_addPayload(lua_State* L)
  * @return packetCount/stack - Total packet processed by RNA.
  * @todo maintain a single copy and return the same copy with every call to Detector_getFlow().
  */
-static int Detector_getFlow(lua_State* L)
+static int detector_get_flow(lua_State* L)
 {
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
@@ -1285,11 +1183,11 @@ static int Detector_getFlow(lua_State* L)
     lua_pushvalue(L, -1);
     df->userDataRef = luaL_ref(L, LUA_REGISTRYINDEX);
 
-    sflist_add_tail(&allocatedFlowList, df);
+    LuaDetectorManager::add_detector_flow(df);
     return 1;
 }
 
-int Detector_addHttpPattern(lua_State* L)
+int detector_add_http_pattern(lua_State* L)
 {
     int index = 1;
 
@@ -1370,13 +1268,9 @@ int Detector_addHttpPattern(lua_State* L)
 /*  On the lua side, this should look something like:
         addSSLCertPattern(<appId>, '<pattern string>' )
 */
-int Detector_addSSLCertPattern(lua_State* L)
+int detector_add_ssl_cert_pattern(lua_State* L)
 {
-    uint8_t* pattern_str;
-    size_t pattern_size;
     int index = 1;
-    uint8_t type;
-    AppId app_id;
 
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
     if ( ud->validateParams.pkt )
@@ -1385,9 +1279,9 @@ int Detector_addSSLCertPattern(lua_State* L)
         return 0;
     }
 
-    type = lua_tointeger(L, index++);
-    app_id  = (AppId)lua_tointeger(L, index++);
-    pattern_size = 0;
+    uint8_t type = lua_tointeger(L, index++);
+    AppId app_id  = (AppId)lua_tointeger(L, index++);
+    size_t pattern_size = 0;
     const char* tmpString = lua_tolstring(L, index++, &pattern_size);
     if (!tmpString || !pattern_size)
     {
@@ -1396,7 +1290,7 @@ int Detector_addSSLCertPattern(lua_State* L)
     }
 
 #ifdef REMOVED_WHILE_NOT_IN_USE
-    pattern_str = (uint8_t*)snort_strdup(tmpString);
+    uint8_t* pattern_str = (uint8_t*)snort_strdup(tmpString);
     if (!ssl_add_cert_pattern(pattern_str, pattern_size, type, app_id,
         &ud->appid_config->serviceSslConfig))
     {
@@ -1405,7 +1299,6 @@ int Detector_addSSLCertPattern(lua_State* L)
         return 0;
     }
 #else
-    UNUSED(pattern_str);
     UNUSED(type);
 #endif
 
@@ -1413,16 +1306,10 @@ int Detector_addSSLCertPattern(lua_State* L)
     return 0;
 }
 
-/*  On the lua side, this should look something like:
-        addDNSHostPattern(<appId>, '<pattern string>' )
-*/
-int Detector_addDNSHostPattern(lua_State* L)
+// for Lua this looks something like: addDNSHostPattern(<appId>, '<pattern string>')
+int detector_add_dns_host_pattern(lua_State* L)
 {
-    uint8_t* pattern_str;
-    size_t pattern_size;
     int index = 1;
-    uint8_t type;
-    AppId app_id;
 
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
     if ( ud->validateParams.pkt )
@@ -1431,17 +1318,18 @@ int Detector_addDNSHostPattern(lua_State* L)
         return 0;
     }
 
-    type = lua_tointeger(L, index++);
-    app_id  = (AppId)lua_tointeger(L, index++);
+    uint8_t type = lua_tointeger(L, index++);
+    AppId app_id = (AppId)lua_tointeger(L, index++);
 
-    pattern_size = 0;
+    size_t pattern_size = 0;
     const char* tmpString = lua_tolstring(L, index++, &pattern_size);
     if (!tmpString || !pattern_size)
     {
         ErrorMessage("LuaDetectorApi:Invalid DNS Host pattern string");
         return 0;
     }
-    pattern_str = (uint8_t*)snort_strdup(tmpString);
+
+    uint8_t* pattern_str = (uint8_t*)snort_strdup(tmpString);
     if (!dns_add_host_pattern(pattern_str, pattern_size, type, app_id))
     {
         snort_free(pattern_str);
@@ -1451,13 +1339,9 @@ int Detector_addDNSHostPattern(lua_State* L)
     return 0;
 }
 
-static int Detector_addSSLCnamePattern(lua_State* L)
+static int detector_add_ssl_cname_pattern(lua_State* L)
 {
-    uint8_t* pattern_str;
-    size_t pattern_size;
     int index = 1;
-    uint8_t type;
-    AppId app_id;
 
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
     if ( ud->validateParams.pkt )
@@ -1466,10 +1350,10 @@ static int Detector_addSSLCnamePattern(lua_State* L)
         return 0;
     }
 
-    type = lua_tointeger(L, index++);
-    app_id  = (AppId)lua_tointeger(L, index++);
+    uint8_t type = lua_tointeger(L, index++);
+    AppId app_id  = (AppId)lua_tointeger(L, index++);
 
-    pattern_size = 0;
+    size_t pattern_size = 0;
     const char* tmpString = lua_tolstring(L, index++, &pattern_size);
     if (!tmpString || !pattern_size)
     {
@@ -1478,7 +1362,7 @@ static int Detector_addSSLCnamePattern(lua_State* L)
     }
 
 #ifdef REMOVED_WHILE_NOT_IN_USE
-    pattern_str = (uint8_t*)snort_strdup(tmpString);
+    uint8_t* pattern_str = (uint8_t*)snort_strdup(tmpString);
     if (!ssl_add_cname_pattern(pattern_str, pattern_size, type, app_id,
         &ud->appid_config->serviceSslConfig))
     {
@@ -1487,7 +1371,6 @@ static int Detector_addSSLCnamePattern(lua_State* L)
         return 0;
     }
 #else
-    UNUSED(pattern_str);
     UNUSED(type);
 #endif
 
@@ -1495,13 +1378,9 @@ static int Detector_addSSLCnamePattern(lua_State* L)
     return 0;
 }
 
-static int Detector_addHostPortApp(lua_State* L)
+static int detector_add_host_port_application(lua_State* L)
 {
-    /*uint8_t *ipaddr_str; */
-    size_t ipaddr_size;
     int index = 1;
-    uint8_t type;
-    AppId app_id;
     sfip_t ip_addr;
 
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
@@ -1511,11 +1390,11 @@ static int Detector_addHostPortApp(lua_State* L)
         return 0;
     }
 
-    type = lua_tointeger(L, index++);
-    app_id  = (AppId)lua_tointeger(L, index++);
-    ipaddr_size = 0;
+    uint8_t type = lua_tointeger(L, index++);
+    AppId app_id  = (AppId)lua_tointeger(L, index++);
+    size_t ipaddr_size = 0;
     const char* ip_str= lua_tolstring(L, index++, &ipaddr_size);
-    if (!ip_str || !ipaddr_size || !ConvertStringToAddress(ip_str, &ip_addr))
+    if (!ip_str || !ipaddr_size || !convert_string_to_address(ip_str, &ip_addr))
     {
         ErrorMessage("%s: Invalid IP address: %s\n",__func__, ip_str);
         return 0;
@@ -1531,30 +1410,25 @@ static int Detector_addHostPortApp(lua_State* L)
     }
 
     if (!hostPortAppCacheAdd(&ip_addr, (uint16_t)port, (IpProtocol)proto, type, app_id))
-    {
         ErrorMessage("%s:Failed to backend call\n",__func__);
-    }
 
     return 0;
 }
 
-static int Detector_addContentTypePattern(lua_State* L)
+static int detector_add_content_type_pattern(lua_State* L)
 {
-    uint8_t* pattern;
-    AppId appId;
     int index = 1;
-
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
-
     size_t stringSize = 0;
+
     const char* tmpString = lua_tolstring(L, index++, &stringSize);
     if (!tmpString || !stringSize)
     {
         ErrorMessage("Invalid HTTP Header string");
         return 0;
     }
-    pattern = (uint8_t*)snort_strdup(tmpString);
-    appId = lua_tointeger(L, index++);
+    uint8_t* pattern = (uint8_t*)snort_strdup(tmpString);
+    AppId appId = lua_tointeger(L, index++);
 
     if (ud->validateParams.pkt)
     {
@@ -1574,7 +1448,7 @@ static int Detector_addContentTypePattern(lua_State* L)
     return 0;
 }
 
-static inline int GetDetectorUserData(lua_State* L, int index,
+static inline int get_detector_user_data(lua_State* L, int index,
     UserData<Detector>** detector_user_data, const char* errorString)
 {
     // Verify detector user data and that we are not in packet context
@@ -1588,7 +1462,7 @@ static inline int GetDetectorUserData(lua_State* L, int index,
     return 0;
 }
 
-static int detector_create_chp_app(AppId appIdInstance, unsigned app_type_flags, int num_matches)
+static int create_chp_application(AppId appIdInstance, unsigned app_type_flags, int num_matches)
 {
     CHPApp* new_app = (CHPApp*)snort_calloc(sizeof(CHPApp));
     new_app->appIdInstance = appIdInstance;
@@ -1605,24 +1479,20 @@ static int detector_create_chp_app(AppId appIdInstance, unsigned app_type_flags,
     return 0;
 }
 
-static int Detector_CHPCreateApp(lua_State* L)
+static int detector_chp_create_application(lua_State* L)
 {
     UserData<Detector>* ud;
-    AppId appId;
-    unsigned app_type_flags;
-    int num_matches;
-    AppId appIdInstance;
     int index = 1;
 
-    if (GetDetectorUserData(L, index++, &ud,
+    if (get_detector_user_data(L, index++, &ud,
         "LuaDetectorApi:Invalid HTTP detector user data in CHPCreateApp."))
         return 0;
 
-    appId = lua_tointeger(L, index++);
-    appIdInstance = CHP_APPID_SINGLE_INSTANCE(appId); // Last instance for the old API
+    AppId appId = lua_tointeger(L, index++);
+    AppId appIdInstance = CHP_APPID_SINGLE_INSTANCE(appId); // Last instance for the old API
 
-    app_type_flags =    lua_tointeger(L, index++);
-    num_matches =       lua_tointeger(L, index++);
+    unsigned app_type_flags =    lua_tointeger(L, index++);
+    int num_matches =       lua_tointeger(L, index++);
 
     // We only want one of these for each appId.
     if (sfxhash_find(CHP_glossary, &appIdInstance))
@@ -1633,16 +1503,16 @@ static int Detector_CHPCreateApp(lua_State* L)
         return 0;
     }
 
-    detector_create_chp_app(appIdInstance, app_type_flags, num_matches);
+    create_chp_application(appIdInstance, app_type_flags, num_matches);
     return 0;
 }
 
-static inline int CHPGetKeyPatternBoolean(lua_State* L, int index)
+static inline int get_chp_key_pattern_boolean(lua_State* L, int index)
 {
     return (0 != lua_tointeger(L, index));
 }
 
-static inline int CHPGetPatternType(lua_State* L, int index, PatternType* pattern_type)
+static inline int get_chp_pattern_type(lua_State* L, int index, PatternType* pattern_type)
 {
     *pattern_type = (PatternType)lua_tointeger(L, index);
     if (*pattern_type < AGENT_PT || *pattern_type > MAX_PATTERN_TYPE)
@@ -1653,7 +1523,7 @@ static inline int CHPGetPatternType(lua_State* L, int index, PatternType* patter
     return 0;
 }
 
-static inline int CHPGetPatternDataAndSize(lua_State* L, int index, char** pattern_data,
+static inline int get_chp_pattern_data_and_size(lua_State* L, int index, char** pattern_data,
     size_t* pattern_size)
 {
     const char* tmpString = nullptr; // Lua owns this pointer
@@ -1670,7 +1540,7 @@ static inline int CHPGetPatternDataAndSize(lua_State* L, int index, char** patte
     return 0;
 }
 
-static inline int CHPGetActionType(lua_State* L, int index, ActionType* action_type)
+static inline int get_chp_action_type(lua_State* L, int index, ActionType* action_type)
 {
     *action_type = (ActionType)lua_tointeger(L, index);
     if (*action_type < NO_ACTION || *action_type > MAX_ACTION_TYPE)
@@ -1683,7 +1553,7 @@ static inline int CHPGetActionType(lua_State* L, int index, ActionType* action_t
     return 0;
 }
 
-static inline int CHPGetActionData(lua_State* L, int index, char** action_data)
+static inline int get_chp_action_data(lua_State* L, int index, char** action_data)
 {
     // An empty string is translated into a nullptr pointer because the action data is optional
     const char* tmpString = nullptr; // Lua owns this pointer
@@ -1697,10 +1567,9 @@ static inline int CHPGetActionData(lua_State* L, int index, char** action_data)
     return 0;
 }
 
-static int detector_add_chp_action(AppId appIdInstance, int isKeyPattern, PatternType patternType,
+static int add_chp_pattern_action(AppId appIdInstance, int isKeyPattern, PatternType patternType,
         size_t patternSize, char* patternData, ActionType actionType, char* optionalActionData)
 {
-    uint precedence;
     CHPListElement* chpa;
     CHPApp* chpapp;
     AppInfoManager& app_info_mgr = AppInfoManager::get_instance();
@@ -1726,7 +1595,8 @@ static int detector_add_chp_action(AppId appIdInstance, int isKeyPattern, Patter
 
     if (chpapp->ptype_scan_counts[patternType] == 0)
         chpapp->num_scans++;
-    precedence = chpapp->ptype_scan_counts[patternType]++;
+
+    unsigned precedence = chpapp->ptype_scan_counts[patternType]++;
     // at runtime we'll want to know how many of each type of pattern we are looking for.
     if (actionType == REWRITE_FIELD || actionType == INSERT_FIELD)
     {
@@ -1775,95 +1645,77 @@ static int detector_add_chp_action(AppId appIdInstance, int isKeyPattern, Patter
 
     /* Set the safe-search bits in the appId entry */
     if (actionType == GET_OFFSETS_FROM_REBUILT)
-    {
-        /* This is a search engine and it is SUPPORTED for safe-search packet rewrite */
         app_info_mgr.set_app_info_flags(CHP_APPIDINSTANCE_TO_ID(appIdInstance), APPINFO_FLAG_SEARCH_ENGINE |
             APPINFO_FLAG_SUPPORTED_SEARCH);
-    }
     else if (actionType == SEARCH_UNSUPPORTED)
-    {
-        /* This is a search engine and it is UNSUPPORTED for safe-search packet rewrite */
         app_info_mgr.set_app_info_flags(CHP_APPIDINSTANCE_TO_ID(appIdInstance), APPINFO_FLAG_SEARCH_ENGINE);
-    }
     else if (actionType == DEFER_TO_SIMPLE_DETECT && strcmp(patternData,"<ignore-all-patterns>") == 0)
-    {
         remove_http_patterns_for_id(appIdInstance);
-    }
 
     return 0;
 }
 
-static int Detector_CHPAddAction(lua_State* L)
+static int detector_add_chp_action(lua_State* L)
 {
     UserData<Detector>* ud;
-    int key_pattern;
     PatternType ptype;
     size_t psize;
     char* pattern;
     ActionType action;
     char* action_data;
-
-    AppId appIdInstance;
-    AppId appId;
-
     int index = 1;
 
-    if (GetDetectorUserData(L, index++, &ud,
+    if (get_detector_user_data(L, index++, &ud,
         "LuaDetectorApi:Invalid HTTP detector user data in CHPAddAction."))
         return 0;
 
     // Parameter 1
-    appId = lua_tointeger(L, index++);
-    appIdInstance = CHP_APPID_SINGLE_INSTANCE(appId); // Last instance for the old API
+    AppId appId = lua_tointeger(L, index++);
+    AppId appIdInstance = CHP_APPID_SINGLE_INSTANCE(appId); // Last instance for the old API
 
     // Parameter 2
-    key_pattern = CHPGetKeyPatternBoolean(L, index++);
+    int key_pattern = get_chp_key_pattern_boolean(L, index++);
 
     // Parameter 3
-    if (CHPGetPatternType(L, index++, &ptype))
+    if (get_chp_pattern_type(L, index++, &ptype))
         return 0;
 
     // Parameter 4
-    if (CHPGetPatternDataAndSize(L, index++, &pattern, &psize))
+    if (get_chp_pattern_data_and_size(L, index++, &pattern, &psize))
         return 0;
 
     // Parameter 5
-    if (CHPGetActionType(L, index++, &action))
+    if (get_chp_action_type(L, index++, &action))
     {
         snort_free(pattern);
         return 0;
     }
 
     // Parameter 6
-    if (CHPGetActionData(L, index++, &action_data))
+    if (get_chp_action_data(L, index++, &action_data))
     {
         snort_free(pattern);
         return 0;
     }
 
-    return detector_add_chp_action(appIdInstance, key_pattern, ptype, psize, pattern,
+    return add_chp_pattern_action(appIdInstance, key_pattern, ptype, psize, pattern,
             action, action_data);
 }
 
-static int Detector_CHPMultiCreateApp(lua_State* L)
+static int detector_create_chp_multi_application(lua_State* L)
 {
     UserData<Detector>* ud;
-    AppId appId;
-    unsigned app_type_flags;
-    int num_matches;
-
     AppId appIdInstance;
     int instance;
-
     int index = 1;
 
-    if (GetDetectorUserData(L, index++, &ud,
+    if (get_detector_user_data(L, index++, &ud,
         "LuaDetectorApi:Invalid HTTP detector user data in CHPMultiCreateApp."))
         return 0;
 
-    appId =             lua_tointeger(L, index++);
-    app_type_flags =    lua_tointeger(L, index++);
-    num_matches =       lua_tointeger(L, index++);
+    AppId appId = lua_tointeger(L, index++);
+    unsigned app_type_flags = lua_tointeger(L, index++);
+    int num_matches = lua_tointeger(L, index++);
 
     for (instance=0; instance < CHP_APPID_INSTANCE_MAX; instance++ )
     {
@@ -1881,64 +1733,60 @@ static int Detector_CHPMultiCreateApp(lua_State* L)
         return 0;
     }
 
-    if ( detector_create_chp_app(appIdInstance, app_type_flags, num_matches) )
+    if ( create_chp_application(appIdInstance, app_type_flags, num_matches) )
         return 0;
 
     lua_pushnumber(L, appIdInstance);
     return 1;
 }
 
-static int Detector_CHPMultiAddAction(lua_State* L)
+static int detector_add_chp_multi_action(lua_State* L)
 {
     UserData<Detector>* ud;
-    int key_pattern;
     PatternType ptype;
     size_t psize;
     char* pattern;
     ActionType action;
     char* action_data;
-
-    AppId appIdInstance;
-
     int index = 1;
 
-    if (GetDetectorUserData(L, index++, &ud,
+    if (get_detector_user_data(L, index++, &ud,
         "LuaDetectorApi:Invalid HTTP detector user data in CHPMultiAddAction."))
         return 0;
 
     // Parameter 1
-    appIdInstance = lua_tointeger(L, index++);
+    AppId appIdInstance = lua_tointeger(L, index++);
 
     // Parameter 2
-    key_pattern = CHPGetKeyPatternBoolean(L, index++);
+    int key_pattern = get_chp_key_pattern_boolean(L, index++);
 
     // Parameter 3
-    if (CHPGetPatternType(L, index++, &ptype))
+    if (get_chp_pattern_type(L, index++, &ptype))
         return 0;
 
     // Parameter 4
-    if (CHPGetPatternDataAndSize(L, index++, &pattern, &psize))
+    if (get_chp_pattern_data_and_size(L, index++, &pattern, &psize))
         return 0;
 
     // Parameter 5
-    if (CHPGetActionType(L, index++, &action))
+    if (get_chp_action_type(L, index++, &action))
     {
         snort_free(pattern);
         return 0;
     }
 
     // Parameter 6
-    if (CHPGetActionData(L, index++, &action_data))
+    if (get_chp_action_data(L, index++, &action_data))
     {
         snort_free(pattern);
         return 0;
     }
 
-    return detector_add_chp_action(appIdInstance, key_pattern, ptype, psize, pattern,
+    return add_chp_pattern_action(appIdInstance, key_pattern, ptype, psize, pattern,
             action, action_data);
 }
 
-static int Detector_portOnlyService(lua_State* L)
+static int detector_port_only_service(lua_State* L)
 {
     int index = 1;
 
@@ -1981,7 +1829,7 @@ static int Detector_portOnlyService(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return status/stack - 0 if successful, -1 otherwise.
  */
-static int Detector_lengthAppCacheAdd(lua_State* L)
+static int detector_add_length_app_cache(lua_State* L)
 {
     int i;
     const char* str_ptr;
@@ -2079,7 +1927,7 @@ static int Detector_lengthAppCacheAdd(lua_State* L)
     return 1;
 }
 
-static int Detector_AFAddApp(lua_State* L)
+static int detector_add_af_application(lua_State* L)
 {
     int index = 1;
 
@@ -2098,7 +1946,7 @@ static int Detector_AFAddApp(lua_State* L)
     return 0;
 }
 
-static int Detector_addAppUrl(lua_State* L)
+static int detector_add_url_application(lua_State* L)
 {
     int index = 1;
     const char* tmpString;
@@ -2197,7 +2045,7 @@ static int Detector_addAppUrl(lua_State* L)
     return 0;
 }
 
-static int Detector_addRTMPUrl(lua_State* L)
+static int detector_add_rtmp_url(lua_State* L)
 {
     int index = 1;
     const char* tmpString;
@@ -2296,7 +2144,7 @@ static int Detector_addRTMPUrl(lua_State* L)
 }
 
 /*Lua should inject patterns in <clienAppId, clientVersion, multi-Pattern> format. */
-static int Detector_addSipUserAgent(lua_State* L)
+static int detector_add_sip_user_agent(lua_State* L)
 {
     int index = 1;
 
@@ -2332,7 +2180,7 @@ static int Detector_addSipUserAgent(lua_State* L)
     return 0;
 }
 
-static int openCreateApp(lua_State* L)
+static int create_custom_application(lua_State* L)
 {
     int index = 1;
     const char* tmpString;
@@ -2367,13 +2215,13 @@ static int openCreateApp(lua_State* L)
     return 1;   /*number of results */
 }
 
-static int openAddClientApp(lua_State* L)
+static int add_client_application(lua_State* L)
 {
-    unsigned int serviceAppId, clienAppId;
+    unsigned int serviceAppId, clientAppId;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
     serviceAppId = lua_tonumber(L, 2);
-    clienAppId = lua_tonumber(L, 3);
+    clientAppId = lua_tonumber(L, 3);
 
     // check inputs and whether this function is called in context of a packet
     if ( !ud->validateParams.pkt )
@@ -2389,7 +2237,7 @@ static int openAddClientApp(lua_State* L)
     }
 
     ud->client.appModule.api->add_app(ud->validateParams.asd, serviceAppId,
-        clienAppId, "");
+        clientAppId, "");
 
     lua_pushnumber(L, 0);
     return 1;
@@ -2405,7 +2253,7 @@ static int openAddClientApp(lua_State* L)
  * @return int - Number of elements on stack, which is always 1.
  * @return int/stack - values from enum SERVICE_RETCODE
  */
-static int openAddServiceApp(lua_State* L)
+static int add_service_application(lua_State* L)
 {
     unsigned int serviceId, retValue = SERVICE_ENULL;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
@@ -2425,7 +2273,7 @@ static int openAddServiceApp(lua_State* L)
     return 1;
 }
 
-static int openAddPayloadApp(lua_State* L)
+static int add_payload_application(lua_State* L)
 {
     unsigned int payloadAppId;
 
@@ -2433,8 +2281,7 @@ static int openAddPayloadApp(lua_State* L)
 
     payloadAppId = lua_tonumber(L, 2);
 
-    /*check inputs and whether this function is called in context of a
-      packet */
+    /*check inputs and whether this function is called in context of a packet */
     if ( !ud->validateParams.pkt )
     {
         lua_pushnumber(L, -1);
@@ -2453,7 +2300,7 @@ static int openAddPayloadApp(lua_State* L)
     return 1;
 }
 
-static int openAddHttpPattern(lua_State* L)
+static int add_http_pattern(lua_State* L)
 {
     int index = 1;
 
@@ -2517,7 +2364,7 @@ static int openAddHttpPattern(lua_State* L)
     return 0;
 }
 
-static int openAddUrlPattern(lua_State* L)
+static int add_url_pattern(lua_State* L)
 {
     int index = 1;
     const char* tmpString;
@@ -2613,26 +2460,17 @@ static int openAddUrlPattern(lua_State* L)
  * @param appId/stack        - App ID to use for this detector.
  * @return int - Number of elements on stack, which is always 0.
  */
-static int addPortPatternClient(lua_State* L)
+static int add_port_pattern_client(lua_State* L)
 {
     int index = 1;
-    PortPatternNode* pPattern;
-    IpProtocol protocol;
-    uint16_t port;
-    const char* pattern;
     size_t patternSize = 0;
-    unsigned position;
-    AppId appId;
-
-    /* Verify detector user data and that we are not in packet context */
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
 
-    protocol = (IpProtocol)lua_tonumber(L, index++);
-    //port      = lua_tonumber(L, index++);
-    port = 0;
-    pattern = lua_tolstring(L, index++, &patternSize);
-    position = lua_tonumber(L, index++);
-    appId = lua_tointeger(L, index++);
+    IpProtocol protocol = (IpProtocol)lua_tonumber(L, index++);
+    uint16_t port = 0;      //port      = lua_tonumber(L, index++);  FIXIT-L - why commented out?
+    const char* pattern = lua_tolstring(L, index++, &patternSize);
+    unsigned position = lua_tonumber(L, index++);
+    AppId appId = lua_tointeger(L, index++);
     if (appId <= APP_ID_NONE || !pattern || !patternSize || (protocol != IpProtocol::TCP &&
         protocol !=
         IpProtocol::UDP))
@@ -2642,7 +2480,7 @@ static int addPortPatternClient(lua_State* L)
         return 0;
     }
 
-    pPattern  = (decltype(pPattern))snort_calloc(sizeof(PortPatternNode));
+    PortPatternNode* pPattern  = (decltype(pPattern))snort_calloc(sizeof(PortPatternNode));
     pPattern->pattern  = (decltype(pPattern->pattern))snort_calloc(patternSize);
     pPattern->appId = appId;
     pPattern->protocol = protocol;
@@ -2671,27 +2509,19 @@ static int addPortPatternClient(lua_State* L)
  * @param appId/stack        - App ID to use for this detector.
  * @return int - Number of elements on stack, which is always 0.
  */
-static int addPortPatternService(lua_State* L)
+static int add_port_pattern_service(lua_State* L)
 {
     int index = 1;
     size_t patternSize = 0;
-    PortPatternNode* pPattern;
-    IpProtocol protocol;
-    uint16_t port;
-    const char* pattern;
-    unsigned position;
-    AppId appId;
-
-    /* Verify detector user data and that we are not in packet context */
     auto& ud = *UserData<Detector>::check(L, DETECTOR, index++);
 
-    protocol = (IpProtocol)lua_tonumber(L, index++);
-    port      = lua_tonumber(L, index++);
-    pattern = lua_tolstring(L, index++, &patternSize);
-    position = lua_tonumber(L, index++);
-    appId = lua_tointeger(L, index++);
+    IpProtocol protocol = (IpProtocol)lua_tonumber(L, index++);
+    uint16_t port = lua_tonumber(L, index++);
+    const char* pattern = lua_tolstring(L, index++, &patternSize);
+    unsigned position = lua_tonumber(L, index++);
+    AppId appId = lua_tointeger(L, index++);
 
-    pPattern = (decltype(pPattern))snort_calloc(sizeof(PortPatternNode));
+    PortPatternNode* pPattern = (decltype(pPattern))snort_calloc(sizeof(PortPatternNode));
     pPattern->pattern  = (decltype(pPattern->pattern))snort_calloc(patternSize);
     pPattern->appId = appId;
     pPattern->protocol = protocol;
@@ -2710,7 +2540,7 @@ static int addPortPatternService(lua_State* L)
 }
 
 /*Lua should inject patterns in <clienAppId, clientVersion, multi-Pattern> format. */
-static int Detector_addSipServer(lua_State* L)
+static int detector_add_sip_server(lua_State* L)
 {
     int index = 1;
 
@@ -2774,50 +2604,42 @@ static int Detector_addSipServer(lua_State* L)
  *
  * Example: createFutureFlow("192.168.0.200", 0, "192.168.0.100", 20, 6, 166, 0, 0, 166)
  */
-static int createFutureFlow(lua_State* L)
+static int create_future_flow(lua_State* L)
 {
     sfip_t client_addr;
     sfip_t server_addr;
-    IpProtocol proto;
-    uint16_t client_port, server_port;
-    char* pattern;
-    AppId service_app_id, client_app_id, payload_app_id, app_id_to_snort;
-    int16_t snort_app_id;
-    AppIdSession* fp;
-
+    int16_t snort_app_id = 0;
     auto& ud = *UserData<Detector>::check(L, DETECTOR, 1);
 
     /*check inputs and whether this function is called in context of a packet */
     if ( !ud->validateParams.pkt )
         return 0;
 
-    pattern = (char*)lua_tostring(L, 2);
-    if (!ConvertStringToAddress(pattern, &client_addr))
+    char* pattern = (char*)lua_tostring(L, 2);
+    if (!convert_string_to_address(pattern, &client_addr))
         return 0;
 
-    client_port = lua_tonumber(L, 3);
+    uint16_t client_port = lua_tonumber(L, 3);
 
     pattern = (char*)lua_tostring(L, 4);
-    if (!ConvertStringToAddress(pattern, &server_addr))
+    if (!convert_string_to_address(pattern, &server_addr))
         return 0;
 
-    server_port = lua_tonumber(L, 5);
-    proto = (IpProtocol)lua_tonumber(L, 6);
-    service_app_id = lua_tointeger(L, 7);
-    client_app_id  = lua_tointeger(L, 8);
-    payload_app_id = lua_tointeger(L, 9);
-    app_id_to_snort = lua_tointeger(L, 10);
+    uint16_t server_port = lua_tonumber(L, 5);
+    IpProtocol proto = (IpProtocol)lua_tonumber(L, 6);
+    AppId service_app_id = lua_tointeger(L, 7);
+    AppId client_app_id  = lua_tointeger(L, 8);
+    AppId payload_app_id = lua_tointeger(L, 9);
+    AppId app_id_to_snort = lua_tointeger(L, 10);
     if (app_id_to_snort > APP_ID_NONE)
     {
         AppInfoTableEntry* entry = AppInfoManager::get_instance().get_app_info_entry(app_id_to_snort);
-        if (nullptr == entry)
+        if (!entry)
             return 0;
         snort_app_id = entry->snortId;
     }
-    else
-        snort_app_id = 0;
 
-    fp = AppIdSession::create_future_session(ud->validateParams.pkt,  &client_addr,
+    AppIdSession* fp = AppIdSession::create_future_session(ud->validateParams.pkt,  &client_addr,
             client_port, &server_addr, server_port, proto, snort_app_id,
             APPID_EARLY_SESSION_FLAG_FW_RULE);
     if (fp)
@@ -2836,129 +2658,127 @@ static int createFutureFlow(lua_State* L)
         return 0;
 }
 
-static const luaL_reg Detector_methods[] =
+static const luaL_reg detector_methods[] =
 {
     /* Obsolete API names.  No longer use these!  They are here for backward
      * compatibility and will eventually be removed. */
     /*  - "memcmp" is now "matchSimplePattern" (below) */
-    { "memcmp",                   Detector_memcmp },
+    { "memcmp",                   detector_memcmp },
     /*  - "getProtocolType" is now "getL4Protocol" (below) */
-    { "getProtocolType",          Detector_getProtocolType },
+    { "getProtocolType",          detector_get_protocol_type },
     /*  - "inCompatibleData" is now "markIncompleteData" (below) */
-    { "inCompatibleData",         service_inCompatibleData },
+    { "inCompatibleData",         service_set_incompatible_data },
     /*  - "addDataId" is now "addAppIdDataToFlow" (below) */
-    { "addDataId",                service_addDataId },
+    { "addDataId",                service_add_data_id },
     /*  - "service_inCompatibleData" is now "service_markIncompleteData" (below) */
-    { "service_inCompatibleData", service_inCompatibleData },
+    { "service_inCompatibleData", service_set_incompatible_data },
     /*  - "service_addDataId" is now "service_addAppIdDataToFlow" (below) */
-    { "service_addDataId",        service_addDataId },
-
-    { "getPacketSize",            Detector_getPacketSize },
-    { "getPacketDir",             Detector_getPacketDir },
-    { "matchSimplePattern",       Detector_memcmp },
-    { "getPcreGroups",            Detector_getPcreGroups },
-    { "getL4Protocol",            Detector_getProtocolType },
-    { "getPktSrcAddr",            Detector_getPktSrcIPAddr },
-    { "getPktDstAddr",            Detector_getPktDstIPAddr },
-    { "getPktSrcPort",            Detector_getPktSrcPort },
-    { "getPktDstPort",            Detector_getPktDstPort },
-    { "getPktCount",              Detector_getPktCount },
-    { "getFlow",                  Detector_getFlow },
-    { "htons",                    Detector_htons },
-    { "htonl",                    Detector_htonl },
-    { "log",                      Detector_logMessage },
-    { "addHttpPattern",           Detector_addHttpPattern },
-    { "addAppUrl",                Detector_addAppUrl },
-    { "addRTMPUrl",               Detector_addRTMPUrl },
-    { "addContentTypePattern",    Detector_addContentTypePattern },
-    { "addSSLCertPattern",        Detector_addSSLCertPattern },
-    { "addSipUserAgent",          Detector_addSipUserAgent },
-    { "addSipServer",             Detector_addSipServer },
-    { "addSSLCnamePattern",       Detector_addSSLCnamePattern },
-    { "addHostPortApp",           Detector_addHostPortApp },
-    { "addDNSHostPattern",        Detector_addDNSHostPattern },
+    { "service_addDataId",        service_add_data_id },
+
+    { "getPacketSize",            detector_get_packet_size },
+    { "getPacketDir",             detector_get_packet_direction },
+    { "matchSimplePattern",       detector_memcmp },
+    { "getPcreGroups",            detector_get_pcre_groups },
+    { "getL4Protocol",            detector_get_protocol_type },
+    { "getPktSrcAddr",            detector_get_packet_src_addr },
+    { "getPktDstAddr",            detector_get_packet_dst_addr },
+    { "getPktSrcPort",            detector_get_packet_src_port },
+    { "getPktDstPort",            detector_get_packet_dst_port },
+    { "getPktCount",              detector_get_packet_count },
+    { "getFlow",                  detector_get_flow },
+    { "htons",                    detector_htons },
+    { "htonl",                    detector_htonl },
+    { "log",                      detector_log_message },
+    { "addHttpPattern",           detector_add_http_pattern },
+    { "addAppUrl",                detector_add_url_application },
+    { "addRTMPUrl",               detector_add_rtmp_url },
+    { "addContentTypePattern",    detector_add_content_type_pattern },
+    { "addSSLCertPattern",        detector_add_ssl_cert_pattern },
+    { "addSipUserAgent",          detector_add_sip_user_agent },
+    { "addSipServer",             detector_add_sip_server },
+    { "addSSLCnamePattern",       detector_add_ssl_cname_pattern },
+    { "addHostPortApp",           detector_add_host_port_application },
+    { "addDNSHostPattern",        detector_add_dns_host_pattern },
 
     /*Obsolete - new detectors should not use this API */
     { "init",                     service_init },
-    { "registerPattern",          service_registerPattern },
-    { "getServiceID",             service_getServiceId },
-    { "addPort",                  service_addPorts },
-    { "removePort",               service_removePorts },
-    { "setServiceName",           service_setServiceName },
-    { "getServiceName",           service_getServiceName },
-    { "isCustomDetector",         service_isCustomDetector },
-    { "setValidator",             service_setValidator },
-    { "addService",               service_addService },
-    { "failService",              service_failService },
-    { "inProcessService",         service_inProcessService },
-    { "markIncompleteData",       service_inCompatibleData },
-    { "analyzePayload",           service_analyzePayload },
-    { "addAppIdDataToFlow",       service_addDataId },
+    { "registerPattern",          service_register_pattern },
+    { "getServiceID",             service_get_service_id },
+    { "addPort",                  service_add_ports },
+    { "removePort",               service_remove_ports },
+    { "setServiceName",           service_set_service_name },
+    { "getServiceName",           service_get_service_name },
+    { "isCustomDetector",         service_is_custom_detector },
+    { "setValidator",             service_set_validator },
+    { "addService",               service_add_service },
+    { "failService",              service_fail_service },
+    { "inProcessService",         service_in_process_service },
+    { "markIncompleteData",       service_set_incompatible_data },
+    { "analyzePayload",           service_analyze_payload },
+    { "addAppIdDataToFlow",       service_add_data_id },
 
     /*service API */
-    { "service_init",             service_init },
-    { "service_registerPattern",  service_registerPattern },
-    { "service_getServiceId",     service_getServiceId },
-    { "service_addPort",          service_addPorts },
-    { "service_removePort",       service_removePorts },
-    { "service_setServiceName",   service_setServiceName },
-    { "service_getServiceName",   service_getServiceName },
-    { "service_isCustomDetector", service_isCustomDetector },
-    { "service_setValidator",     service_setValidator },
-    { "service_addService",       service_addService },
-    { "service_failService",      service_failService },
-    { "service_inProcessService", service_inProcessService },
-    { "service_markIncompleteData", service_inCompatibleData },
-    { "service_analyzePayload",   service_analyzePayload },
-    { "service_addAppIdDataToFlow", service_addDataId },
-    { "service_addClient",        service_addClient },
+    { "service_init",               service_init },
+    { "service_registerPattern",    service_register_pattern },
+    { "service_getServiceId",       service_get_service_id },
+    { "service_addPort",            service_add_ports },
+    { "service_removePort",         service_remove_ports },
+    { "service_setServiceName",     service_set_service_name },
+    { "service_getServiceName",     service_get_service_name },
+    { "service_isCustomDetector",   service_is_custom_detector },
+    { "service_setValidator",       service_set_validator },
+    { "service_addService",         service_add_service },
+    { "service_failService",        service_fail_service },
+    { "service_inProcessService",   service_in_process_service },
+    { "service_markIncompleteData", service_set_incompatible_data },
+    { "service_analyzePayload",     service_analyze_payload },
+    { "service_addAppIdDataToFlow", service_add_data_id },
+    { "service_addClient",          service_add_client },
 
     /*client init API */
     { "client_init",              client_init },
-    { "client_registerPattern",   client_registerPattern },
-    { "client_getServiceId",      service_getServiceId },
+    { "client_registerPattern",  client_register_pattern },
+    { "client_getServiceId",      service_get_service_id },
 
     /*client service API */
-    { "client_addApp",            client_addApp },
-    { "client_addInfo",           client_addInfo },
-    { "client_addUser",           client_addUser },
-    { "client_addPayload",        client_addPayload },
+    { "client_addApp",            client_add_application },
+    { "client_addInfo",           client_add_info },
+    { "client_addUser",           client_add_user },
+    { "client_addPayload",        client_add_payload },
 
     //HTTP Multi Pattern engine
-    { "CHPCreateApp",             Detector_CHPCreateApp },
-    { "CHPAddAction",             Detector_CHPAddAction },
-    { "CHPMultiCreateApp",        Detector_CHPMultiCreateApp }, // multiple detectors, same appId
-    { "CHPMultiAddAction",        Detector_CHPMultiAddAction },
+    { "CHPCreateApp",             detector_chp_create_application },
+    { "CHPAddAction",             detector_add_chp_action },
+    { "CHPMultiCreateApp",        detector_create_chp_multi_application }, // multiple detectors, same appId
+    { "CHPMultiAddAction",        detector_add_chp_multi_action },
 
     //App Forecasting engine
-    { "AFAddApp",                 Detector_AFAddApp },
+    { "AFAddApp",                 detector_add_af_application },
 
-    { "portOnlyService",          Detector_portOnlyService },
+    { "portOnlyService",          detector_port_only_service },
 
     /* Length-based detectors. */
-    { "AddLengthBasedDetector",   Detector_lengthAppCacheAdd },
+    { "AddLengthBasedDetector",   detector_add_length_app_cache },
 
-    { "registerAppId",           common_registerAppId },
+    { "registerAppId",            common_register_application_id },
 
-    { "open_createApp",           openCreateApp },
-    { "open_addClientApp",        openAddClientApp },
-    { "open_addServiceApp",       openAddServiceApp },
-    { "open_addPayloadApp",       openAddPayloadApp },
-    { "open_addHttpPattern",      openAddHttpPattern },
-    { "open_addUrlPattern",       openAddUrlPattern },
+    { "open_createApp",           create_custom_application },
+    { "open_addClientApp",        add_client_application },
+    { "open_addServiceApp",       add_service_application },
+    { "open_addPayloadApp",       add_payload_application },
+    { "open_addHttpPattern",      add_http_pattern },
+    { "open_addUrlPattern",       add_url_pattern },
 
-    { "addPortPatternClient",     addPortPatternClient },
-    { "addPortPatternService",    addPortPatternService },
+    { "addPortPatternClient",     add_port_pattern_client },
+    { "addPortPatternService",    add_port_pattern_service },
 
-    { "createFutureFlow",         createFutureFlow },
+    { "createFutureFlow",         create_future_flow },
 
-    { 0, 0 }
+    { nullptr, nullptr }
 };
 
-/**This function performs a clean exit on an api instance. It is called when RNA is performing
- * a clean exit.
- */
-void Detector_fini(void* data)
+// release resources and remove detector resources when snort exits
+void remove_detector(void* data)
 {
     lua_State* myLuaState;
     Detector* detector = (Detector*)data;
@@ -2997,7 +2817,7 @@ void Detector_fini(void* data)
         ErrorMessage("%s: DetectorFini not provided\n", detector->name.c_str());
     }
 
-    freeDetector(detector);
+    delete detector;
 
     /*lua_close will perform garbage collection after killing lua script. */
     /**Design: Lua_state does not allow me to store user variables so detectors store lua_state.
@@ -3049,26 +2869,23 @@ static const luaL_reg Detector_meta[] =
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return methodArray/stack - array of newly created methods
  */
-int Detector_register(lua_State* L)
+int register_detector(lua_State* L)
 {
-    /* populates a new table with Detector_methods (method_table), add the table to the globals and
-       stack*/
-    luaL_openlib(L, DETECTOR, Detector_methods, 0);
+    // populates new table from detector_methods and add it to the globals and stack
+    luaL_openlib(L, DETECTOR, detector_methods, 0);
 
-    /* create metatable for Foo, add it to the Lua registry, metatable on stack */
+    // create metatable for Foo, add it to the Lua registry, metatable on stack
     luaL_newmetatable(L, DETECTOR);
 
-    /* populates table on stack with Detector_meta methods, puts the metatable on stack*/
+    // populates table on stack with Detector_meta methods, puts the metatable on stack
     luaL_openlib(L, nullptr, Detector_meta, 0);
 
     lua_pushliteral(L, "__index");
     lua_pushvalue(L, -3);             /* dup methods table*/
-    lua_settable(L, -3);                /* metatable.__index = methods */
-
+    lua_settable(L, -3);              /* metatable.__index = methods */
     lua_pushliteral(L, "__metatable");
     lua_pushvalue(L, -3);             /* dup methods table*/
-    lua_settable(L, -3);                /* hide metatable:
-                                           metatable.__metatable = methods */
+    lua_settable(L, -3);              /* hide metatable: metatable.__metatable = methods */
     lua_pop(L, 1);                    /* drop metatable */
     return 1;                         /* return methods on the stack */
 }
@@ -3078,6 +2895,13 @@ int Detector_register(lua_State* L)
 // -----------------------------------------------------------------------------
 // Detector
 // -----------------------------------------------------------------------------
+Detector::Detector(AppIdConfig* config)
+    : appid_config(config)
+{
+    // FIXIT-L - client/server modules should initialize themselves to default values
+    memset(&client.appModule, 0, sizeof(RNAClientAppModule));
+    memset(&server.serviceModule, 0, sizeof(RNAServiceValidationModule));
+}
 
 Detector::~Detector()
 {
@@ -3089,6 +2913,4 @@ Detector::~Detector()
         luaL_unref(myLuaState, LUA_REGISTRYINDEX, detectorUserDataRef);
 
     delete pFlow;
-
-    delete[] validatorBuffer;
 }
index 17fec678498043684e7dd1133907f7b311e14de5..bc00e0c73276b9fae5cec6a432f093b9434484b0 100644 (file)
@@ -58,60 +58,57 @@ struct DetectorPackageInfo
     UniInfo server;
 };
 
-struct Detector
+struct ValidateParameters
 {
-    ~Detector();
+    const uint8_t* data = nullptr;
+    uint16_t size = 0;
+    int dir = 0;
+    AppIdSession* asd = nullptr;
+    Packet* pkt = nullptr;
+    uint8_t macAddress[6] = {0};
+};
 
-    bool isCustom;          // true for customer created detectors
-    bool isActive;
-    bool wasActive;
+struct ServerDetectorState
+{
+    unsigned int serviceId = APP_ID_UNKNOWN;
+    RNAServiceValidationModule serviceModule;
+    RNAServiceElement* pServiceElement = nullptr;
+};
 
-    struct
-    {
-        const uint8_t* data;
-        uint16_t size;
-        int dir;
-        AppIdSession* asd;
-        Packet* pkt;
-        uint8_t macAddress[6];
-    } validateParams;
-
-    struct
-    {
-        unsigned int serviceId;
-        RNAServiceValidationModule serviceModule;
-        RNAServiceElement* pServiceElement;
-    } server;
+struct ClientDetectorState
+{
+    unsigned int appFpId;
+    RNAClientAppModule appModule;
+};
 
-    struct
-    {
-        unsigned int appFpId;
-        RNAClientAppModule appModule;
-    } client;
+class Detector
+{
+public:
+    Detector(AppIdConfig* config);
+    ~Detector();
 
-    AppIdSession* pFlow;
-    lua_State* myLuaState;
-    int detectorUserDataRef;    // key into LUA_REGISTRYINDEX
+    bool isCustom = false;
+    bool isActive = false;
+    bool wasActive = false;
+    ValidateParameters validateParams;
+    ServerDetectorState server;
+    ClientDetectorState client;
+    AppIdSession* pFlow = nullptr;
+    lua_State* myLuaState= nullptr;
+    int detectorUserDataRef = 0;    // key into LUA_REGISTRYINDEX
     std::string name;
     DetectorPackageInfo packageInfo;
-    unsigned detector_version;
-    char* validatorBuffer;
-    unsigned char digest[16];
-    AppIdConfig* appid_config;
+    unsigned detector_version = 0;
+    AppIdConfig* appid_config = nullptr;
 };
 
-int Detector_register(lua_State*);
-void Detector_fini(void* detector);
-void detectorRemoveAllPorts(Detector*);
-Detector* createDetector(lua_State*, const char* filename);
-CLIENT_APP_RETCODE validateAnyClientApp(const uint8_t* data, uint16_t size, const int dir,
+int register_detector(lua_State*);
+void remove_detector(void* detector);
+CLIENT_APP_RETCODE validate_client_application(const uint8_t* data, uint16_t size, const int dir,
     AppIdSession*, Packet*, Detector*);
-int Detector_addSSLCertPattern(lua_State*);
-int Detector_addDNSHostPattern(lua_State*);
-int Detector_addHttpPattern(lua_State*);
-int validateAnyService(ServiceValidationArgs*);
-int checkServiceElement(Detector*);
-int init_CHP_glossary();
-void free_CHP_glossary();
+int validate_service_application(ServiceValidationArgs*);
+int check_service_element(Detector*);
+int init_chp_glossary();
+void free_chp_glossary();
 
 #endif
index f0ee66276acd0758485103b1b53a5fb56897a78f..19d224def7d6a4754def83673dee7c73c3ffd784 100644 (file)
@@ -107,7 +107,7 @@ static const uint64_t FLAGS_TABLE_C_TO_LUA[32]
 };
 
 /* Convert flag bits used by the Lua code into what the C code uses. */
-static inline uint64_t ConvertFlagsLuaToC(uint64_t in)
+static inline uint64_t convert_flags_lua_to_c(uint64_t in)
 {
     uint64_t out = 0;
     unsigned i;
@@ -125,7 +125,7 @@ static inline uint64_t ConvertFlagsLuaToC(uint64_t in)
 }
 
 /* Convert flag bits used by the C code into what the Lua code uses. */
-static inline uint64_t ConvertFlagsCToLua(uint64_t in)
+static inline uint64_t convert_flags_c_to_lua(uint64_t in)
 {
     uint64_t out = 0;
     unsigned i;
@@ -154,7 +154,7 @@ static inline uint64_t ConvertFlagsCToLua(uint64_t in)
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return UserData<DetectorFlow>/stack - A userdata representing UserData<DetectorFlow>.
  */
-static int DetectorFlow_new(lua_State* L)
+static int create_detector_flow(lua_State* L)
 {
     sfip_t saddr;
     sfip_t daddr;
@@ -215,7 +215,7 @@ static int DetectorFlow_new(lua_State* L)
     lua_pushvalue(L, -1);
     detector_flow->userDataRef = luaL_ref(L, LUA_REGISTRYINDEX);
 
-    sflist_add_tail(&allocatedFlowList, detector_flow);
+    LuaDetectorManager::add_detector_flow(detector_flow);
 
     detector_flow->asd = AppIdSession::create_future_session(detector_data->validateParams.pkt, &saddr,
             sport, &daddr, dport, proto, 0, 0);
@@ -230,9 +230,8 @@ static int DetectorFlow_new(lua_State* L)
     return 1;
 }
 
-/**free DetectorFlow and its corresponding user data.
- */
-void freeDetectorFlow(void* userdata)
+// free DetectorFlow and its corresponding user data.
+void free_detector_flow(void* userdata)
 {
     DetectorFlow* detector_flow = (DetectorFlow*)userdata;
 
@@ -254,7 +253,7 @@ void freeDetectorFlow(void* userdata)
  * @param flags/stack - flags to be set.
  * @return int - Number of elements on stack, which is 0
  */
-static int DetectorFlow_setFlowFlag(lua_State* L)
+static int set_detector_flow_flag(lua_State* L)
 {
     uint64_t flags;
 
@@ -262,7 +261,7 @@ static int DetectorFlow_setFlowFlag(lua_State* L)
     assert(pLuaData.ptr);
 
     flags = lua_tonumber(L, 2);
-    flags = ConvertFlagsLuaToC(flags);
+    flags = convert_flags_lua_to_c(flags);
 
     pLuaData->asd->set_session_flags(flags);
 
@@ -277,7 +276,7 @@ static int DetectorFlow_setFlowFlag(lua_State* L)
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return flagValue/stack - value of a given flag.
  */
-static int DetectorFlow_getFlowFlag(lua_State* L)
+static int get_detector_flow_flag(lua_State* L)
 {
     uint64_t flags;
     uint64_t ret;
@@ -286,10 +285,10 @@ static int DetectorFlow_getFlowFlag(lua_State* L)
     assert(pLuaData.ptr);
 
     flags = lua_tonumber(L, 2);
-    flags = ConvertFlagsLuaToC(flags);
+    flags = convert_flags_lua_to_c(flags);
 
     ret = pLuaData->asd->get_session_flags(flags);
-    ret = ConvertFlagsCToLua(ret);
+    ret = convert_flags_c_to_lua(ret);
     lua_pushnumber(L, ret);
 
     return 1;
@@ -302,7 +301,7 @@ static int DetectorFlow_getFlowFlag(lua_State* L)
  * @param flags/stack - flags to be cleared.
  * @return int - Number of elements on stack, which is 0.
  */
-static int DetectorFlow_clearFlowFlag(lua_State* L)
+static int clear_detector_flow_flag(lua_State* L)
 {
     uint64_t flags;
 
@@ -310,7 +309,7 @@ static int DetectorFlow_clearFlowFlag(lua_State* L)
     assert(pLuaData.ptr);
 
     flags = lua_tonumber(L, 2);
-    flags = ConvertFlagsLuaToC(flags);
+    flags = convert_flags_lua_to_c(flags);
 
     pLuaData->asd->clear_session_flags(flags);
 
@@ -324,7 +323,7 @@ static int DetectorFlow_clearFlowFlag(lua_State* L)
  * @param serviceId/stack - service Id to be set on a flow.
  * @return int - Number of elements on stack, which is 0.
  */
-static int DetectorFlow_setFlowServiceId(lua_State*)
+static int set_detector_flow_service_id(lua_State*)
 { return 0; }
 
 /**Set client application id on a flow.
@@ -334,7 +333,7 @@ static int DetectorFlow_setFlowServiceId(lua_State*)
  * @param applId/stack - client application Id to be set on a flow.
  * @return int - Number of elements on stack, which is 0.
  */
-static int DetectorFlow_setFlowClnAppId(lua_State* )
+static int set_detecter_flow_cln_app_id(lua_State* )
 {
     return 0;
 }
@@ -346,7 +345,7 @@ static int DetectorFlow_setFlowClnAppId(lua_State* )
  * @param applTypeId/stack - client application type id to be set on a flow.
  * @return int - Number of elements on stack, which is 0.
  */
-static int DetectorFlow_setFlowClnAppType(lua_State*)
+static int set_detector_flow_cln_app_type(lua_State*)
 {
     return 0;
 }
@@ -365,7 +364,7 @@ static int DetectorFlow_setFlowClnAppType(lua_State*)
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return flowKey/stack - A 20 byte flow key
  */
-static int DetectorFlow_getFlowKey(lua_State* L)
+static int get_detector_flow_key(lua_State* L)
 {
     auto& pLuaData = *UserData<DetectorFlow>::check(L, DETECTORFLOW, 1);
     assert(pLuaData.ptr);
@@ -376,32 +375,30 @@ static int DetectorFlow_getFlowKey(lua_State* L)
     return 1;
 }
 
-static const luaL_reg DetectorFlow_methods[] =
+static const luaL_reg detector_flow_api[] =
 {
     /* Obsolete API names.  No longer use these!  They are here for backward
      * compatibility and will eventually be removed. */
     /*  - "new" is now "createFlow" (below) */
-    { "new",                      DetectorFlow_new },
-    { "createFlow",               DetectorFlow_new },
-    { "setFlowFlag",              DetectorFlow_setFlowFlag },
-    { "getFlowFlag",              DetectorFlow_getFlowFlag },
-    { "clearFlowFlag",            DetectorFlow_clearFlowFlag },
-    { "setFlowServiceId",         DetectorFlow_setFlowServiceId },
-    { "setFlowClnAppId",         DetectorFlow_setFlowClnAppId },
-    { "setFlowClnAppType",       DetectorFlow_setFlowClnAppType },
-    { "getFlowKey",               DetectorFlow_getFlowKey },
-    { 0, 0 }
+    { "new",                create_detector_flow },
+    { "createFlow",         create_detector_flow },
+    { "setFlowFlag",        set_detector_flow_flag },
+    { "getFlowFlag",        get_detector_flow_flag },
+    { "clearFlowFlag",      clear_detector_flow_flag },
+    { "setFlowServiceId",   set_detector_flow_service_id },
+    { "setFlowClnAppId",    set_detecter_flow_cln_app_id },
+    { "setFlowClnAppType",  set_detector_flow_cln_app_type },
+    { "getFlowKey",         get_detector_flow_key },
+    { nullptr, nullptr }
 };
 
-/**
- * lua_close will ensure that all detectors and flows get _gc called.
- */
-static int DetectorFlow_gc(lua_State*)
+// lua_close will ensure that all detectors and flows get _gc called.
+static int gc_detector_flow(lua_State*)
 {
     return 0;
 }
 
-static int DetectorFlow_tostring(lua_State* L)
+static int detector_flow_tostring(lua_State* L)
 {
     char buff[32];
     snprintf(buff, sizeof(buff), "%p", (void*)UserData<DetectorFlow>::check(L, DETECTORFLOW, 1));
@@ -409,10 +406,10 @@ static int DetectorFlow_tostring(lua_State* L)
     return 1;
 }
 
-static const luaL_reg DetectorFlow_meta[] =
+static const luaL_reg detector_flow_meta[] =
 {
-    { "__gc",       DetectorFlow_gc },
-    { "__tostring", DetectorFlow_tostring },
+    { "__gc",       gc_detector_flow },
+    { "__tostring", detector_flow_tostring },
     { 0, 0 }
 };
 
@@ -425,29 +422,25 @@ static const luaL_reg DetectorFlow_meta[] =
  * @return int - Number of elements on stack, which is 1 if successful, 0 otherwise.
  * @return methodArray/stack - array of newly created methods
  */
-int DetectorFlow_register(lua_State* L)
+int register_detector_flow_api(lua_State* L)
 {
     /* populates a new table with Detector_methods (method_table), add the table to the globals and
        stack*/
-    luaL_openlib(L, DETECTORFLOW, DetectorFlow_methods, 0);
+    luaL_openlib(L, DETECTORFLOW, detector_flow_api, 0);
 
     /* create metatable for Foo, add it to the Lua registry, metatable on stack */
     luaL_newmetatable(L, DETECTORFLOW);
 
     /* populates table on stack with Detector_meta methods, puts the metatable on stack*/
-    luaL_openlib(L, nullptr, DetectorFlow_meta, 0);
+    luaL_openlib(L, nullptr, detector_flow_meta, 0);
 
     lua_pushliteral(L, "__index");
     lua_pushvalue(L, -3);             /* dup methods table*/
-    lua_settable(L, -3);                /* metatable.__index = methods */
+    lua_settable(L, -3);              /* metatable.__index = methods */
 
     lua_pushliteral(L, "__metatable");
-    lua_pushvalue(L, -3);             /* dup methods table*/
-    lua_settable(L, -3);                /* hide metatable:
-                                           metatable.__metatable = methods */
-    lua_pop(L, 1);                    /* drop metatable */
-    return 1;                         /* return methods on the stack */
+    lua_pushvalue(L, -3);               /* dup methods table*/
+    lua_settable(L, -3);                /* hide metatable: metatable.__metatable = methods */
+    lua_pop(L, 1);                      /* drop metatable */
+    return 1;                           /* return methods on the stack */
 }
-
-/** @} */ /* end of LuaDetectorFlowApi */
-
index ec3c0ce793afa3bd9f7dab480cdc71c03a340811..4bb2f805b6ec79ed9d04e94e2f8066466e987686 100644 (file)
@@ -35,7 +35,7 @@ struct DetectorFlow
     int userDataRef;
 };
 
-int DetectorFlow_register(lua_State*);
-void freeDetectorFlow(void* userdata);
+int register_detector_flow_api(lua_State*);
+void free_detector_flow(void* userdata);
 
 #endif
index 3e5f041f17e416a6b0bf6ab9812d717deb24426d..75e51795b4cd012ae2d24020bed76a7f5175f4f1 100644 (file)
 #include <algorithm>
 #include <glob.h>
 #include <lua.hpp>
-#include <openssl/md5.h>
 
 #include "appid_config.h"
 #include "client_plugins/client_app_base.h"
 #include "service_plugins/service_base.h"
-#include "fw_appid.h" // for lua*PerfStats
-#include "hash/sfghash.h"
 #include "log/messages.h"
 #include "lua/lua.h"
+#include "lua_detector_util.h"
 #include "lua_detector_api.h"
 #include "lua_detector_flow_api.h"
 #include "main/snort_debug.h"
 #include "utils/util.h"
 
-#define MD5CONTEXT MD5_CTX
+#define MAX_LUA_DETECTOR_FILENAME_LEN 1024
+#define MAX_DEFAULT_NUM_LUA_TRACKERS  10000
+#define AVG_LUA_TRACKER_SIZE_IN_BYTES 740
+#define MAX_MEMORY_FOR_LUA_DETECTORS (512 * 1024 * 1024)
 
-#define MD5INIT    MD5_Init
-#define MD5UPDATE  MD5_Update
-#define MD5FINAL   MD5_Final
-#define MD5DIGEST  MD5
-
-#define MAXPD 1024
-#define LUA_DETECTOR_FILENAME_MAX 1024
-
-THREAD_LOCAL SF_LIST allocatedFlowList;  /*list of flows allocated. */
+THREAD_LOCAL SF_LIST allocated_detector_flow_list;  /*list of flows allocated. */
+THREAD_LOCAL LuaDetectorManager* lua_detector_mgr;
 
 static inline bool match_char_set(char c, const char* set)
 {
@@ -156,11 +150,11 @@ static lua_State* create_lua_state()
     auto L = luaL_newstate();
     luaL_openlibs(L);
 
-    Detector_register(L);
+    register_detector(L);
     // After detector register the methods are still on the stack, remove them
     lua_pop(L, 1);
 
-    DetectorFlow_register(L);
+    register_detector_flow_api(L);
     lua_pop(L, 1);
 
 #ifdef REMOVED_WHILE_NOT_IN_USE
@@ -279,9 +273,10 @@ static void clean_client_detector(Detector* detector)
     }
 }
 
-LuaDetectorManager::LuaDetectorManager()
+LuaDetectorManager::LuaDetectorManager(AppIdConfig& config) :
+                config(config)
 {
-    sflist_init(&allocatedFlowList);
+    sflist_init(&allocated_detector_flow_list);
     allocated_detectors.clear();
 }
 
@@ -295,10 +290,39 @@ LuaDetectorManager::~LuaDetectorManager()
         delete detector;
     }
 
-    sflist_static_free_all(&allocatedFlowList, freeDetectorFlow);
+    sflist_static_free_all(&allocated_detector_flow_list, free_detector_flow);
     allocated_detectors.clear();
 }
 
+void LuaDetectorManager::initialize(AppIdConfig& config)
+{
+    static bool lua_detectors_listed = false;
+
+    lua_detector_mgr = new LuaDetectorManager(config);
+    lua_detector_mgr->initialize_lua_detectors();
+    lua_detector_mgr->activate_lua_detectors();
+    if(config.mod_config->debug && !lua_detectors_listed)
+    {
+        lua_detector_mgr->list_lua_detectors();
+        lua_detectors_listed = false;
+    }
+}
+
+void LuaDetectorManager::terminate()
+{
+    delete lua_detector_mgr;
+}
+
+void LuaDetectorManager::add_detector_flow(DetectorFlow* df)
+{
+    sflist_add_tail(&allocated_detector_flow_list, df);
+}
+
+void LuaDetectorManager::free_detector_flows()
+{
+    sflist_static_free_all(&allocated_detector_flow_list, free_detector_flow);
+}
+
 /**calculates Number of flow and host tracker entries for Lua detectors, given amount
  * of memory allocated to RNA (fraction of total system memory) and number of detectors
  * loaded in database. Calculations are based on CAICCI detector and observing memory
@@ -307,9 +331,6 @@ LuaDetectorManager::~LuaDetectorManager()
  * total system memory.
  * @param numDetectors - number of lua detectors present in database.
  */
-#define LUA_TRACKERS_MAX  10000
-#define LUA_TRACKER_AVG_MEM_BYTES  740
-
 static inline void set_lua_tracker_size(lua_State* L, uint32_t numTrackers)
 {
     /*change flow tracker size according to available memory calculation */
@@ -321,16 +342,18 @@ static inline void set_lua_tracker_size(lua_State* L, uint32_t numTrackers)
         {
             lua_pushinteger (L, numTrackers);
             if (lua_pcall(L, 1, 0, 0) != 0)
-                ErrorMessage("error setting tracker size");
+                ErrorMessage("Error activating lua detector. Setting tracker size to %u failed.\n",
+                             numTrackers);
         }
     }
     else
     {
         DebugMessage(DEBUG_LOG, "hostServiceTrackerModule.setHosServiceTrackerSize not found");
     }
+
     lua_pop(L, 1);
 
-    /*change flow tracker size according to available memory calculation */
+    // change flow tracker size according to available memory calculation
     lua_getglobal(L, "flowTrackerModule");
     if (lua_istable(L, -1))
     {
@@ -346,6 +369,7 @@ static inline void set_lua_tracker_size(lua_State* L, uint32_t numTrackers)
     {
         DebugMessage(DEBUG_LOG, "flowTrackerModule.setFlowTrackerSize not found");
     }
+
     lua_pop(L, 1);
 }
 
@@ -356,45 +380,56 @@ static inline uint32_t compute_lua_tracker_size(uint64_t rnaMemory, uint32_t num
 
     if (!numDetectors)
         numDetectors = 1;
-    numTrackers = (detectorMemory / LUA_TRACKER_AVG_MEM_BYTES) / numDetectors;
-    return (numTrackers > LUA_TRACKERS_MAX) ? LUA_TRACKERS_MAX : numTrackers;
+    numTrackers = (detectorMemory / AVG_LUA_TRACKER_SIZE_IN_BYTES) / numDetectors;
+    return (numTrackers > MAX_DEFAULT_NUM_LUA_TRACKERS) ? MAX_DEFAULT_NUM_LUA_TRACKERS : numTrackers;
 }
 
-void LuaDetectorManager::initialize_lua_detector( const char* detectorName, char* validator,
-        unsigned int validatorLen, unsigned char* const digest, AppIdConfig* pConfig,
-        bool isCustom)
+// FIXIT-M lifetime of detector is easy to misuse with this idiom
+// Leaves 1 value (the Detector userdata) at the top of the stack
+static Detector* create_lua_detector(lua_State* L, const char* detectorName, AppIdConfig* config)
 {
-    Detector* detector;
+    auto detector = new Detector(config);
+    detector->myLuaState = L;
+    detector->name = detectorName;
+
+    UserData<Detector>::push(L, DETECTOR, detector);
+
+    // add a lua reference so the detector doesn't get garbage-collected
+    lua_pushvalue(L, -1);
+    detector->detectorUserDataRef = luaL_ref(L, LUA_REGISTRYINDEX);
+    return detector;
+}
+
+void LuaDetectorManager::load_detector( const char* detector_filename, bool isCustom)
+{
+    char detectorName[MAX_LUA_DETECTOR_FILENAME_LEN];
 
     lua_State* L = create_lua_state();
     if ( !L )
     {
         ErrorMessage("can not create new luaState");
-        delete[] validator;
         return;
     }
 
-    if ( luaL_loadbuffer(L, validator, validatorLen, "<buffer>") || lua_pcall(L, 0, 0, 0) )
+    if ( luaL_loadfile(L, detector_filename) || lua_pcall(L, 0, 0, 0) )
     {
-        ErrorMessage("cannot run validator %s, error: %s\n", detectorName, lua_tostring(L, -1));
+        ErrorMessage("Error loading Lua detector: %s : %s\n", detector_filename, lua_tostring(L, -1));
         lua_close(L);
-        delete[] validator;
         return;
     }
 
-    detector = createDetector(L, detectorName);
+    snprintf(detectorName, MAX_LUA_DETECTOR_FILENAME_LEN, "%s_%s",
+        (isCustom ? "custom" : "cisco"), basename(detector_filename));
+    Detector* detector = create_lua_detector(L, detectorName, &config);
     if ( !detector )
     {
         ErrorMessage("cannot allocate detector %s\n", detectorName);
         lua_close(L);
-        delete[] validator;
         return;
     }
 
     get_detector_package_info(detector);
-    detector->validatorBuffer = validator;
     detector->isActive = true;
-    detector->appid_config =  pConfig;
     detector->isCustom = isCustom;
 
     if ( detector->packageInfo.server.initFunctionName.empty() )
@@ -404,7 +439,7 @@ void LuaDetectorManager::initialize_lua_detector( const char* detectorName, char
         cam = &detector->client.appModule;
         cam->name = detector->packageInfo.name.c_str();
         cam->proto = detector->packageInfo.proto;
-        cam->validate = validateAnyClientApp;
+        cam->validate = validate_client_application;
         cam->minimum_matches = detector->packageInfo.client.minimum_matches;
         cam->userData = detector;
         cam->api = getClientApi();
@@ -415,115 +450,41 @@ void LuaDetectorManager::initialize_lua_detector( const char* detectorName, char
         detector->server.serviceId = APP_ID_UNKNOWN;
 
         /*create a ServiceElement */
-        if (checkServiceElement(detector))
+        if (check_service_element(detector))
         {
-            detector->server.pServiceElement->validate = validateAnyService;
+            detector->server.pServiceElement->validate = validate_service_application;
             detector->server.pServiceElement->userdata = detector;
             detector->server.pServiceElement->detectorType = DETECTOR_TYPE_DECODER;
         }
     }
 
-    memcpy(detector->digest, digest, sizeof(detector->digest));
     allocated_detectors.push_front(detector);
     num_lua_detectors++;
 
     DebugFormat(DEBUG_LOG,"Loaded detector %s\n", detectorName);
 }
 
-void LuaDetectorManager::validate_lua_detector(const char* path, AppIdConfig* pConfig, bool isCustom)
+void LuaDetectorManager::load_lua_detectors(const char* path, bool isCustom)
 {
-    unsigned n;
-    FILE* file;
     char pattern[PATH_MAX];
     snprintf(pattern, sizeof(pattern), "%s/*", path);
 
+    // FIXIT-M - is glob thread safe?
     glob_t globs;
     memset(&globs, 0, sizeof(globs));
     int rval = glob(pattern, 0, nullptr, &globs);
-    if (rval != 0 && rval != GLOB_NOMATCH)
+    if (rval == 0 )
     {
-        ErrorMessage("Unable to read directory '%s'\n",pattern);
-        return;
-    }
+        for (unsigned n = 0; n < globs.gl_pathc; n++)
+            load_detector(globs.gl_pathv[n], isCustom);
 
-    // Open each RNA detector file and gather detector information from it
-    for (n = 0; n < globs.gl_pathc; n++)
-    {
-        unsigned char digest[16];
-        MD5CONTEXT context;
-        char detectorName[LUA_DETECTOR_FILENAME_MAX];
-        char* basename;
-
-        basename = strrchr(globs.gl_pathv[n], '/');
-        if (!basename)
-            basename = globs.gl_pathv[n];
-        basename++;
-
-        snprintf(detectorName, LUA_DETECTOR_FILENAME_MAX, "%s_%s", (isCustom ? "custom" : "cisco"),
-            basename);
-
-        if ((file = fopen(globs.gl_pathv[n], "r")) == nullptr)
-        {
-            ErrorMessage("Unable to read lua detector '%s'\n",globs.gl_pathv[n]);
-            continue;
-        }
-
-        /*Load lua file as a detector. */
-        if (fseek(file, 0, SEEK_END))
-        {
-            ErrorMessage("Unable to seek lua detector '%s'\n",globs.gl_pathv[n]);
-            continue;
-        }
-
-        auto validatorBufferLen = ftell(file);
-        if (validatorBufferLen == -1)
-        {
-            ErrorMessage("Unable to return offset on lua detector '%s'\n",globs.gl_pathv[n]);
-            continue;
-        }
-        if (fseek(file, 0, SEEK_SET))
-        {
-            ErrorMessage("Unable to seek lua detector '%s'\n",globs.gl_pathv[n]);
-            continue;
-        }
-
-        auto validatorBuffer = new uint8_t[validatorBufferLen + 1]();
-        if (fread(validatorBuffer, validatorBufferLen, 1, file) == 0)
-        {
-            ErrorMessage("Failed to read lua detector %s\n",globs.gl_pathv[n]);
-            delete[] validatorBuffer;
-            continue;
-        }
-
-        validatorBuffer[validatorBufferLen] = '\0';
-        MD5INIT(&context);
-        MD5UPDATE(&context, validatorBuffer, validatorBufferLen);
-        MD5FINAL(digest, &context);
-
-        // FIXIT-M this finds the wrong detector -- it should be find_last_of
-        auto it = std::find_if(
-            allocated_detectors.begin(),
-            allocated_detectors.end(),
-            [&detectorName](const Detector* d) {
-            return d->name == detectorName;
-        });
-
-        if ( it != allocated_detectors.end() )
-        {
-            Detector* detector = *it;
-            if ( !memcmp(digest, detector->digest, sizeof(digest)) )
-            {
-                detector->isActive = true;
-                detector->appid_config = pConfig;
-                delete[] validatorBuffer;
-            }
-        }
-
-        initialize_lua_detector(detectorName, (char*)validatorBuffer, validatorBufferLen, digest, pConfig,
-            isCustom);
+        globfree(&globs);
     }
-
-    globfree(&globs);
+    else if(rval == GLOB_NOMATCH)
+        WarningMessage("No lua detectors found in directory '%s'\n", pattern);
+    else
+        ErrorMessage("Error reading lua detectors directory '%s'. Error Code: %d\n",
+                     pattern, rval);
 }
 
 // These functions call the 'DetectorInit' function of the lua detector.
@@ -579,13 +540,9 @@ static void init_client_detector(Detector* detector)
     /*second parameter is a table containing configuration stuff. */
     // ... which is empty.???
     lua_newtable(L);
-
     if ( lua_pcall(L, 2, 1, 0) )
-    {
         ErrorMessage("Could not initialize the %s client app element: %s\n",
             detector->name.c_str(), lua_tostring(L, -1));
-        return;
-    }
 }
 
 void LuaDetectorManager::init_lua_service_detectors()
@@ -616,7 +573,7 @@ void LuaDetectorManager::activate_lua_detectors()
                     detector->server.pServiceElement->ref_count;
         }
 
-    lua_tracker_size = compute_lua_tracker_size(512*1024*1024, num_active_lua_detectors);
+    lua_tracker_size = compute_lua_tracker_size(MAX_MEMORY_FOR_LUA_DETECTORS, num_active_lua_detectors);
     for ( auto& detector : allocated_detectors )
     {
         if ( detector->isActive )
@@ -624,15 +581,16 @@ void LuaDetectorManager::activate_lua_detectors()
     }
 }
 
-void LuaDetectorManager::load_lua_detectors(AppIdConfig* pConfig)
+void LuaDetectorManager::initialize_lua_detectors()
 {
     char path[PATH_MAX];
+
     snprintf(path, sizeof(path), "%s/odp/lua",
             AppIdConfig::get_appid_config()->mod_config->app_detector_dir);
-    validate_lua_detector(path, pConfig, 0);
+    load_lua_detectors(path, false);
     snprintf(path, sizeof(path), "%s/custom/lua",
             AppIdConfig::get_appid_config()->mod_config->app_detector_dir);
-    validate_lua_detector(path, pConfig, 1);
+    load_lua_detectors(path, true);
 }
 
 void LuaDetectorManager::list_lua_detectors()
index f0bbb71eb609a2d4cf35fdb2302b07f712f1da71..4bb72a53186f0c7d5cbdfb11280637fb23a97ee4 100644 (file)
 #ifndef LUA_DETECTOR_MODULE_H
 #define LUA_DETECTOR_MODULE_H
 
-#include <string>
 #include <list>
 
 #include "main/thread.h"
 #include "utils/sflsq.h"
 
 class AppIdConfig;
-struct Detector;
+class Detector;
+struct DetectorFlow;
 
 class LuaDetectorManager
 {
 public:
-    LuaDetectorManager();
+    LuaDetectorManager(AppIdConfig&);
     ~LuaDetectorManager();
+    static void initialize(AppIdConfig&);
+    static void terminate();
+    static void add_detector_flow(DetectorFlow*);
+    static void free_detector_flows();
 
-    void load_lua_detectors(AppIdConfig*);
+private:
+    void initialize_lua_detectors();
     void activate_lua_detectors();
     void list_lua_detectors();
-
-private:
     void init_lua_service_detectors();
     void init_lua_client_detectors();
-    void initialize_lua_detector(const char* detectorName, char* validator, unsigned int validatorLen,
-            unsigned char* const digest, AppIdConfig*, bool isCustom);
-    void validate_lua_detector(const char* path, AppIdConfig*, bool isCustom);
+    void load_detector(const char* detectorName, bool isCustom);
+    void load_lua_detectors(const char* path, bool isCustom);
 
+    AppIdConfig& config;
     std::list<Detector*> allocated_detectors;
 
     // FIXIT-L make these perf counters
@@ -56,7 +59,5 @@ private:
     uint32_t num_active_lua_detectors = 0;
 };
 
-extern THREAD_LOCAL SF_LIST allocatedFlowList;
-
 #endif
 
index 1af223c49fb83e176752ff69cc9cecec35df3eab..701894d2c045586b85e407c3cf158fcc1fb9a583 100644 (file)
@@ -26,7 +26,7 @@
 
 class AppIdConfig;
 class AppIdSession;
-struct Detector;
+class Detector;
 struct RNAServiceSubtype;
 struct Packet;
 struct DynamicPreprocessorData;
@@ -52,7 +52,7 @@ struct ServiceValidationArgs
     int dir;
     AppIdSession* asd;
     Packet* pkt;
-    struct Detector* userdata;
+    Detector* userdata;
     const AppIdConfig* pConfig;
     bool session_logging_enabled;
     char* session_logging_id;
index 412bb05f1b69d01449df67207509692f7871b85e..a91481b0dded1c37dc46bd51633cf0057ae1c31f 100644 (file)
@@ -183,7 +183,7 @@ const ServiceApi serviceapi =
 
 /*C service API */
 static void ServiceRegisterPattern(RNAServiceValidationFCN, IpProtocol, const uint8_t*, unsigned,
-    int, struct Detector*, int, const char* );
+    int, Detector*, int, const char* );
 static void CServiceRegisterPattern(RNAServiceValidationFCN, IpProtocol, const uint8_t*, unsigned,
     int, const char*);
 static void ServiceRegisterPatternUser(RNAServiceValidationFCN, IpProtocol, const uint8_t*,
@@ -440,7 +440,7 @@ const RNAServiceElement* get_service_element(RNAServiceValidationFCN fcn, Detect
 }
 
 static void ServiceRegisterPattern(RNAServiceValidationFCN fcn, IpProtocol proto,
-        const uint8_t* pattern, unsigned size, int position, struct Detector* userdata,
+        const uint8_t* pattern, unsigned size, int position, Detector* userdata,
         int provides_user, const char* name)
 {
     SearchTool** patterns;
@@ -520,7 +520,7 @@ static void ServiceRegisterPattern(RNAServiceValidationFCN fcn, IpProtocol proto
 
 void ServiceRegisterPatternDetector(RNAServiceValidationFCN fcn,
     IpProtocol proto, const uint8_t* pattern, unsigned size,
-    int position, struct Detector* userdata, const char* name)
+    int position, Detector* userdata, const char* name)
 {
     ServiceRegisterPattern(fcn, proto, pattern, size, position, userdata, 0, name);
 }
@@ -538,7 +538,7 @@ static void CServiceRegisterPattern(RNAServiceValidationFCN fcn, IpProtocol prot
 }
 
 static void RemoveServicePortsByType(RNAServiceValidationFCN validate, SF_LIST** services,
-    RNAServiceElement* list, struct Detector* userdata)
+    RNAServiceElement* list, Detector* userdata)
 {
     RNAServiceElement* li;
     unsigned i;
@@ -609,7 +609,7 @@ static void RemoveAllServicePorts()
     }
 }
 
-void ServiceRemovePorts(RNAServiceValidationFCN validate, struct Detector* userdata)
+void ServiceRemovePorts(RNAServiceValidationFCN validate, Detector* userdata)
 {
     RemoveServicePortsByType(validate, service_config->tcp_services,
         service_config->tcp_service_list, userdata);
@@ -625,7 +625,7 @@ static void CServiceRemovePorts(RNAServiceValidationFCN validate)
 }
 
 int ServiceAddPort(const RNAServiceValidationPort* pp, RNAServiceValidationModule* svm,
-    struct Detector* userdata)
+    Detector* userdata)
 {
     SF_LIST** services;
     RNAServiceElement** list = nullptr;
@@ -1410,8 +1410,8 @@ int AppIdServiceIncompatibleData(AppIdSession* asd, const Packet* pkt, int dir,
 
     asd->serviceAppId = APP_ID_NONE;
 
-    if (asd->get_session_flags(APPID_SESSION_IGNORE_HOST|APPID_SESSION_UDP_REVERSED) || (svc_element &&
-        !svc_element->current_ref_count))
+    if (asd->get_session_flags(APPID_SESSION_IGNORE_HOST | APPID_SESSION_UDP_REVERSED)
+                    || (svc_element && !svc_element->current_ref_count))
         return SERVICE_SUCCESS;
 
     if (dir == APP_ID_FROM_INITIATOR)
@@ -1428,8 +1428,8 @@ int AppIdServiceIncompatibleData(AppIdSession* asd, const Packet* pkt, int dir,
         ip = pkt->ptrs.ip_api.get_src();
         port = asd->service_port ? asd->service_port : pkt->ptrs.sp;
 
-        if (!(id_state = add_service_id_state(ip, asd->protocol, port, AppIdServiceDetectionLevel(
-                asd))))
+        if (!(id_state = add_service_id_state(ip, asd->protocol, port,
+                                              AppIdServiceDetectionLevel(asd))))
         {
             ErrorMessage("Incompatible service failed to create state");
             return SERVICE_ENOMEM;
index c952587b8a71c7550fbd97b13ad6494e172bce57..c9e6c64a56825423ecdeeec3f581c9fade161908 100644 (file)
@@ -36,7 +36,7 @@ struct DHCPData;
 struct FpSMBData;
 struct Packet;
 struct ServiceMatch;
-struct Detector;
+class Detector;
 struct RNAServiceValidationPort;
 struct RNAServiceValidationModule;
 
index 2e140cab6e329fc5ce25f219527ad6cc9cf12fae..062b4066a15ec1deaab56824a0def9e3b6250414 100644 (file)
@@ -254,6 +254,7 @@ static int rpc_init(const InitServiceAPI* const init_api)
         {
             if (rpc->r_name)
             {
+                // FIXIT-M - the memory allocate here may not be freed...
                 prog = (RPCProgram*)snort_calloc(sizeof(RPCProgram));
                 prog->program = rpc->r_number;
                 prog->next = rpc_programs;