Refactor find_script() to use parameterized prepared statements (via execute_prepared()) for safer SQL execution.

v3.0_restapi_improvement
Rahim Kanji 2 months ago
parent 14aef13827
commit 79df69332d

@ -31,17 +31,22 @@ private:
}
const std::shared_ptr<http_response> find_script(const http_request& req, std::string& script, int &interval_ms) {
char *error=NULL;
const string req_uri { req.get_path_piece(1) };
const string req_path { req.get_path() };
const string select_query {
"SELECT * FROM runtime_restapi_routes WHERE uri='" + req_uri + "' and"
" method='" + req.get_method() + "' and active=1"
};
std::unique_ptr<SQLite3_result> resultset {
std::unique_ptr<SQLite3_result>(GloAdmin->admindb->execute_statement(select_query.c_str(), &error))
};
const string select_query { "SELECT * FROM runtime_restapi_routes WHERE uri=?1 AND method=?2 AND active=1" };
std::unique_ptr<SQLite3_result> resultset = nullptr;
char* error = NULL;
int cols = 0;
int affected_rows = 0;
auto [rc, statement1] = GloAdmin->admindb->prepare_v2(select_query.c_str());
ASSERT_SQLITE_OK(rc, GloAdmin->admindb);
rc = (*proxy_sqlite3_bind_text)(statement1.get(), 1, req_uri.c_str(), -1, SQLITE_TRANSIENT); ASSERT_SQLITE_OK(rc, GloAdmin->admindb);
rc = (*proxy_sqlite3_bind_text)(statement1.get(), 2, req.get_method().c_str(), -1, SQLITE_TRANSIENT); ASSERT_SQLITE_OK(rc, GloAdmin->admindb);
resultset = std::unique_ptr<SQLite3_result>(GloAdmin->admindb->execute_prepared(statement1.get(), &error, &cols, &affected_rows));
rc = (*proxy_sqlite3_clear_bindings)(statement1.get()); ASSERT_SQLITE_OK(rc, GloAdmin->admindb);
rc = (*proxy_sqlite3_reset)(statement1.get()); ASSERT_SQLITE_OK(rc, GloAdmin->admindb);
if (!resultset) {
proxy_error(

@ -428,7 +428,7 @@ __exit_execute_statement:
/**
* @brief Executes a prepared SQL statement and returns the result set.
*
* @param str The SQL statement to execute.
* @param statement The prepared SQL statement to execute.
* @param _error Pointer to a variable to store the error message.
* @param _cols Pointer to a variable to store the number of columns.
* @param _affected_rows Pointer to a variable to store the number of affected rows.
@ -466,7 +466,6 @@ bool SQLite3DB::execute_prepared(sqlite3_stmt* statement, char** error, int* col
int rc;
*error = NULL;
bool ret = false;
VALGRIND_DISABLE_ERROR_REPORTING;
*cols = (*proxy_sqlite3_column_count)(statement);
if (*cols == 0) { // not a SELECT
*resultset = NULL;
@ -475,6 +474,10 @@ bool SQLite3DB::execute_prepared(sqlite3_stmt* statement, char** error, int* col
do {
rc = (*proxy_sqlite3_step)(statement);
if (rc == SQLITE_LOCKED || rc == SQLITE_BUSY) { // the execution of the prepared statement failed because locked
if ((*proxy_sqlite3_get_autocommit)(db) == 0) {
*error = strdup((*proxy_sqlite3_errmsg)(db));
goto __exit_execute_prepared;
}
usleep(USLEEP_SQLITE_LOCKED);
}
} while (rc == SQLITE_LOCKED || rc == SQLITE_BUSY);

Loading…
Cancel
Save