You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

522 lines
12 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
la_mojo: fix memory leaks and heap corruption Continuous leaks: - protocolParser: on package-pool overflow the oldest package was removed but never freed while the newest (still pooled) one was freed. Every packet a handler does not consume (e.g. other sensors on a shared bus) leaked once the pool was full. Free the removed package, free pooled packages in the destructor and getPackage(), use memmove for the overlapping buffer shifts. - SQLite_Connector::Query: loop only while sqlite3_step() returns SQLITE_ROW. Looping until SQLITE_DONE spun forever allocating rows on SQLITE_BUSY/ERROR. Set a busy timeout, close handles after a failed open, fix escapeBinary() writing into uninitialised buffers. - basicThread/basicDualThread: threads that ended by themselves were never joined, leaking their stacks on every stream drop/restart. Always join once (detach when called from the thread itself); check pthread_create result correctly. - curlRequest: free the header list; initialise m_pPostData and the content type; curlRequestsManager deletes requests it cannot queue. - kernelModuleModemManager: free the phonebook ID list on every reload. - deviceNodeFactory: do not append the same pending node every cycle. - streamHandler: free frames left in the encoding queue on destruction. Heap corruption: - kernelModuleFactory: module that failed to start was deleted twice. - mojoRemoteClient: basicRing::push() returns an ID (may be 0), not a bool; compare with -1. Fix packetExtractor and destructor leaks. - utilizeBasicEvent: payloads are malloc'ed, release with free(). - videoAVLIBSource: avoid sws context double free, NULL check order. - trim(): memmove for overlapping copy. Smaller leaks: dropSession duplicate query, LRF upload data, report backupper / fly hunter settings, Kafka consumer handle, BVMS uniq ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0139veDo3XyavMuVhdnHcN16
4 days ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "sqlite_class.h"
  2. #define LOG(X) m_pLog->Log("SQDB", this, X)
  3. #define LOG_ERROR(X) m_pLog->Log("SQDB", this, _LOG_ERROR, X)
  4. static bool sqlite_global_config_is_set = false;
  5. static uint8_t sqlite_global_inctances_count = 0;
  6. // https://www.sqlite.org/recovery.html
  7. /*
  8. // *
  9. // ** This function is called to recover data from the database.
  10. // * /
  11. static int recoverDatabase(sqlite3 *db){
  12. int rc; // Return code from this routine
  13. const char *zLAF = "lost_and_found"; // Name of "lost_and_found" table
  14. int bFreelist = 1; // True to scan the freelist
  15. int bRowids = 1; // True to restore ROWID values
  16. sqlite3_recover *p; // The recovery object
  17. p = sqlite3_recover_init_sql(db, "main", recoverSqlCb, 0);
  18. sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
  19. sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
  20. sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
  21. sqlite3_recover_run(p);
  22. if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
  23. const char *zErr = sqlite3_recover_errmsg(p);
  24. int errCode = sqlite3_recover_errcode(p);
  25. if( eVerbosity>0 ){
  26. printf("recovery error: %s (%d)\n", zErr, errCode);
  27. }
  28. }
  29. rc = sqlite3_recover_finish(p);
  30. if( eVerbosity>0 && rc ){
  31. printf("recovery returns error code %d\n", rc);
  32. }
  33. return rc;
  34. }
  35. // *
  36. // ** This function is called to recover data from the database. A script
  37. // ** to construct a new database containing all recovered data is output
  38. // ** on stream pState->out.
  39. // * /
  40. static int recoverDatabaseCmd(ShellState *pState, int nArg, char **azArg){
  41. int rc = SQLITE_OK;
  42. const char *zRecoveryDb = ""; // Name of "recovery" database. Debug only
  43. const char *zLAF = "lost_and_found";
  44. int bFreelist = 1; // 0 if --ignore-freelist is specified
  45. int bRowids = 1; // 0 if --no-rowids
  46. sqlite3_recover *p = 0;
  47. int i = 0;
  48. for(i=1; i<nArg; i++){
  49. char *z = azArg[i];
  50. int n;
  51. if( z[0]=='-' && z[1]=='-' ) z++;
  52. n = strlen30(z);
  53. if( n<=17 && memcmp("-ignore-freelist", z, n)==0 ){
  54. bFreelist = 0;
  55. }else
  56. if( n<=12 && memcmp("-recovery-db", z, n)==0 && i<(nArg-1) ){
  57. // This option determines the name of the ATTACH-ed database used
  58. // internally by the recovery extension. The default is "" which
  59. // means to use a temporary database that is automatically deleted
  60. // when closed. This option is undocumented and might disappear at
  61. // any moment.
  62. i++;
  63. zRecoveryDb = azArg[i];
  64. }else
  65. if( n<=15 && memcmp("-lost-and-found", z, n)==0 && i<(nArg-1) ){
  66. i++;
  67. zLAF = azArg[i];
  68. }else
  69. if( n<=10 && memcmp("-no-rowids", z, n)==0 ){
  70. bRowids = 0;
  71. }
  72. else{
  73. utf8_printf(stderr, "unexpected option: %s\n", azArg[i]);
  74. showHelp(pState->out, azArg[0]);
  75. return 1;
  76. }
  77. }
  78. p = sqlite3_recover_init_sql(
  79. pState->db, "main", recoverSqlCb, (void*)pState
  80. );
  81. sqlite3_recover_config(p, 789, (void*)zRecoveryDb); // Debug use only
  82. sqlite3_recover_config(p, SQLITE_RECOVER_LOST_AND_FOUND, (void*)zLAF);
  83. sqlite3_recover_config(p, SQLITE_RECOVER_ROWIDS, (void*)&bRowids);
  84. sqlite3_recover_config(p, SQLITE_RECOVER_FREELIST_CORRUPT,(void*)&bFreelist);
  85. sqlite3_recover_run(p);
  86. if( sqlite3_recover_errcode(p)!=SQLITE_OK ){
  87. const char *zErr = sqlite3_recover_errmsg(p);
  88. int errCode = sqlite3_recover_errcode(p);
  89. raw_printf(stderr, "sql error: %s (%d)\n", zErr, errCode);
  90. }
  91. rc = sqlite3_recover_finish(p);
  92. return rc;
  93. }
  94. */
  95. static void errorLogCallback(void * pArg, int iErrCode, const char * zMsg)
  96. {
  97. char tB[1024];
  98. sprintf(tB, "(%d) %s", iErrCode, zMsg);
  99. basicLogCollection::getInstance()->Log("SQDB_G", pArg, tB);
  100. }
  101. SQLite_Connector::SQLite_Connector()
  102. {
  103. m_pLog = basicLogCollection::getInstance();
  104. m_bIsConnected = false;
  105. m_bPersistentConnection = false;
  106. m_pDBLink = NULL;
  107. m_nBusyTimeoutMs = SQLITE_BUSY_TIMEOUT_MS;
  108. if (! sqlite_global_config_is_set)
  109. {
  110. // if( SQLITE_OK != sqlite3_config(int, ...) ){ SQLITE_MISUSE
  111. sqlite3_config(SQLITE_CONFIG_LOG, errorLogCallback, this);
  112. sqlite3_initialize();
  113. sqlite_global_config_is_set = true;
  114. };
  115. sqlite_global_inctances_count++;
  116. }
  117. SQLite_Connector::~SQLite_Connector()
  118. {
  119. m_bIsConnected = ! Disconnect();
  120. if (sqlite_global_inctances_count == 1)
  121. {
  122. sqlite3_shutdown();
  123. };
  124. sqlite_global_inctances_count--;
  125. }
  126. bool SQLite_Connector::Connect(CSTR FileName, int AUX_FLAGS, bool Persistent)
  127. {
  128. m_mAccessMutex.lock();
  129. m_bPersistentConnection = Persistent;
  130. if (m_bIsConnected)
  131. {
  132. #ifdef DEBUG_ALL
  133. LOG("Connected -> Disconnect!");
  134. #endif
  135. m_bIsConnected = false;
  136. if (m_pDBLink != NULL)
  137. {
  138. if (SQLITE_OK != sqlite3_close(m_pDBLink))
  139. {
  140. m_mAccessMutex.unlock();
  141. return false;
  142. };
  143. };
  144. };
  145. sprintf(m_pDBName, "%s", FileName);
  146. m_nFLAGS = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | AUX_FLAGS;
  147. if (m_bPersistentConnection)
  148. {
  149. #ifdef DEBUG_ALL
  150. LOG("Making Connection....");
  151. #endif
  152. if (SQLITE_OK == sqlite3_open_v2(m_pDBName, &m_pDBLink, m_nFLAGS, NULL))
  153. {
  154. applyBusyTimeout();
  155. m_bIsConnected = true;
  156. }
  157. else if (m_pDBLink != NULL)
  158. {
  159. // sqlite3_open_v2 allocates a handle even on failure
  160. sqlite3_close(m_pDBLink);
  161. m_pDBLink = NULL;
  162. }
  163. #ifdef DEBUG_ALL
  164. LOG("Done!");
  165. #endif
  166. }
  167. else
  168. {
  169. m_bIsConnected = true;
  170. };
  171. m_mAccessMutex.unlock();
  172. return m_bIsConnected;
  173. }
  174. void SQLite_Connector::applyBusyTimeout(void)
  175. {
  176. if (m_pDBLink != NULL)
  177. {
  178. // <= 0 removes the busy handler: a locked database fails with SQLITE_BUSY at once
  179. sqlite3_busy_timeout(m_pDBLink, m_nBusyTimeoutMs > 0 ? m_nBusyTimeoutMs : 0);
  180. };
  181. }
  182. void SQLite_Connector::setBusyTimeout(int ms)
  183. {
  184. m_mAccessMutex.lock();
  185. m_nBusyTimeoutMs = ms > 0 ? ms : 0;
  186. applyBusyTimeout(); // a persistent link is open already; non-persistent ones get it on ReConnect()
  187. m_mAccessMutex.unlock();
  188. }
  189. bool SQLite_Connector::ReConnect(void)
  190. {
  191. if (m_pDBLink != NULL)
  192. {
  193. if (SQLITE_OK != sqlite3_close(m_pDBLink))
  194. {
  195. return false;
  196. }
  197. m_pDBLink = NULL;
  198. }
  199. if (SQLITE_OK == sqlite3_open_v2(m_pDBName, &m_pDBLink, m_nFLAGS, NULL))
  200. {
  201. applyBusyTimeout();
  202. return true;
  203. }
  204. if (m_pDBLink != NULL)
  205. {
  206. // sqlite3_open_v2 allocates a handle even on failure
  207. sqlite3_close(m_pDBLink);
  208. m_pDBLink = NULL;
  209. }
  210. return false;
  211. }
  212. bool SQLite_Connector::Disconnect(void)
  213. {
  214. if (m_pDBLink != NULL)
  215. {
  216. if (SQLITE_OK != sqlite3_close(m_pDBLink))
  217. {
  218. return false;
  219. }
  220. }
  221. m_pDBLink = NULL;
  222. return true;
  223. }
  224. bool SQLite_Connector::SilentQuery(CSTR QS)
  225. {
  226. if (m_bIsConnected)
  227. {
  228. int QSlen = strlen(QS);
  229. m_mAccessMutex.lock();
  230. if (! m_bPersistentConnection)
  231. {
  232. if (! ReConnect())
  233. {
  234. m_mAccessMutex.unlock();
  235. return false;
  236. };
  237. };
  238. sqlite3_stmt * query = NULL;
  239. // if( SQLITE_OK != sqlite3_prepare_v2( m_pDBLink, QS, QSlen, NULL, NULL ) ){
  240. if (SQLITE_OK != sqlite3_prepare_v2(m_pDBLink, QS, QSlen, &query, NULL))
  241. {
  242. m_mAccessMutex.unlock();
  243. return false;
  244. };
  245. #ifdef DEBUG_ALL
  246. LOG(sqlite3_expanded_sql(query));
  247. #endif
  248. int stepRC = sqlite3_step(query);
  249. if (SQLITE_DONE != stepRC)
  250. {
  251. if (SQLITE_ROW != stepRC)
  252. {
  253. char tB[256];
  254. snprintf(tB, sizeof(tB), "SilentQuery step failed (%d): %.200s", stepRC, sqlite3_errmsg(m_pDBLink));
  255. LOG_ERROR(tB);
  256. };
  257. sqlite3_finalize(query);
  258. m_mAccessMutex.unlock();
  259. return false;
  260. };
  261. sqlite3_finalize(query);
  262. if (! m_bPersistentConnection)
  263. {
  264. if (! Disconnect())
  265. {
  266. m_mAccessMutex.unlock();
  267. return false;
  268. };
  269. };
  270. m_mAccessMutex.unlock();
  271. return true;
  272. }
  273. else
  274. {
  275. LOG_ERROR("No Connection to DB!");
  276. };
  277. return false;
  278. }
  279. AAssoc * SQLite_Connector::Query(CSTR QS, bool useCache)
  280. {
  281. AAssoc * RetVal = NULL;
  282. Assoc * tElement;
  283. //unsigned int num_Fields;
  284. sqlite3_stmt * query = NULL;
  285. //char temp[256];
  286. if (useCache)useCache=false;
  287. int QSlen = strlen(QS);
  288. m_mAccessMutex.lock();
  289. if (! m_bPersistentConnection)
  290. {
  291. if (! ReConnect())
  292. {
  293. m_mAccessMutex.unlock();
  294. return RetVal;
  295. };
  296. };
  297. if (SQLITE_OK != sqlite3_prepare_v2(m_pDBLink, QS, QSlen, &query, NULL))
  298. {
  299. m_mAccessMutex.unlock();
  300. return RetVal;
  301. };
  302. #ifdef DEBUG_ALL
  303. LOG(sqlite3_expanded_sql(query));
  304. #endif
  305. RetVal = new AAssoc();
  306. int stepRC;
  307. // Only SQLITE_ROW carries data. Looping until SQLITE_DONE spins forever (allocating a new
  308. // row every iteration) when step returns SQLITE_BUSY / SQLITE_ERROR / SQLITE_MISUSE.
  309. while ((stepRC = sqlite3_step(query)) == SQLITE_ROW)
  310. {
  311. string Key;
  312. string Val;
  313. uint32_t num_cols = sqlite3_column_count(query);
  314. if (num_cols)
  315. {
  316. tElement = new Assoc();
  317. if (tElement)
  318. {
  319. for (uint32_t i = 0; i < num_cols; i++)
  320. {
  321. Key = string(sqlite3_column_name(query, i));
  322. switch (sqlite3_column_type(query, i))
  323. {
  324. case SQLITE_INTEGER: Val = std::string((char *) sqlite3_column_text(query, i)); break;
  325. case SQLITE_FLOAT : Val = std::string((char *) sqlite3_column_text(query, i)); break;
  326. case SQLITE3_TEXT : Val = std::string((char *) sqlite3_column_text(query, i)); break;
  327. default : Val.clear(); break; // NULL / BLOB: don't reuse previous column's value
  328. };
  329. (*tElement)[Key] = Val;
  330. };
  331. RetVal->push_back(tElement);
  332. };
  333. };
  334. };
  335. if (stepRC != SQLITE_DONE)
  336. {
  337. char tB[256];
  338. snprintf(tB, sizeof(tB), "Query step failed (%d): %.200s", stepRC, sqlite3_errmsg(m_pDBLink));
  339. LOG_ERROR(tB);
  340. };
  341. sqlite3_finalize(query);
  342. if (! m_bPersistentConnection)
  343. {
  344. if (! Disconnect())
  345. {
  346. m_mAccessMutex.unlock();
  347. return RetVal;
  348. };
  349. };
  350. m_mAccessMutex.unlock();
  351. return RetVal;
  352. }
  353. #include "../../components/base/basicFunctionality.h"
  354. CSTR SQLite_Connector::escapeString(CSTR value)
  355. {
  356. // CSTR buffer = NULL;
  357. int v_len = strlen(value);
  358. CSTR result = (CSTR) malloc(3 * v_len);
  359. if (result)
  360. {
  361. /*
  362. int idx = 0;
  363. for( int i = 0; i < v_len; i++ ){
  364. //If character is printable
  365. if(isprint( value[i] ) != 0){
  366. strncat( result+idx, value+i, 1 );
  367. idx++;
  368. }else{
  369. char tB[4];
  370. snprintf( tB, 4, "#%02X", value[i]);
  371. strncat( result+idx, tB, 3 );
  372. idx+=3;
  373. };
  374. };
  375. buffer = ( CSTR ) malloc( idx+1 );
  376. if( buffer ) {
  377. strncat( buffer, result, idx );
  378. buffer[idx] = (char)0;
  379. };
  380. free(result);
  381. */
  382. escape_string(result, 3 * v_len, value, v_len);
  383. };
  384. return result;
  385. }
  386. CSTR SQLite_Connector::escapeBinary(uint8_t * value, uint32_t Size)
  387. {
  388. CSTR buffer = NULL;
  389. if (m_bIsConnected)
  390. {
  391. int v_len = Size;
  392. CSTR result = (CSTR) malloc(3 * v_len + 1);
  393. if (result)
  394. {
  395. int idx = 0;
  396. for (int i = 0; i < v_len; i++)
  397. {
  398. // If character is printable
  399. if (isprint(value[i]) != 0)
  400. {
  401. memcpy(result + idx, value + i, 1);
  402. idx++;
  403. }
  404. else
  405. {
  406. char tB[4];
  407. snprintf(tB, 4, "#%02X", value[i]);
  408. memcpy(result + idx, tB, 3); // result is not zero-terminated: strncat was undefined
  409. idx += 3;
  410. };
  411. };
  412. buffer = (CSTR) malloc(idx + 1);
  413. if (buffer)
  414. {
  415. memcpy(buffer, result, idx);
  416. buffer[idx] = (char) 0;
  417. };
  418. free(result);
  419. };
  420. };
  421. return buffer;
  422. }
  423. uint64_t SQLite_Connector::QueryID(CSTR QS)
  424. {
  425. uint64_t RetVal = 0;
  426. uint64_t tVal = 0;
  427. if (m_bIsConnected)
  428. {
  429. //Assoc * tElement;
  430. //unsigned int num_Fields;
  431. sqlite3_stmt * query = NULL;
  432. //char temp[256];
  433. int QSlen = strlen(QS);
  434. m_mAccessMutex.lock();
  435. if (! m_bPersistentConnection)
  436. {
  437. if (! ReConnect())
  438. {
  439. m_mAccessMutex.unlock();
  440. return RetVal;
  441. };
  442. };
  443. if (SQLITE_OK != sqlite3_prepare_v2(m_pDBLink, QS, QSlen, &query, NULL))
  444. {
  445. m_mAccessMutex.unlock();
  446. return RetVal;
  447. };
  448. #ifdef DEBUG_ALL
  449. LOG(sqlite3_expanded_sql(query));
  450. #endif
  451. tVal = sqlite3_last_insert_rowid(m_pDBLink);
  452. if (SQLITE_DONE != sqlite3_step(query))
  453. {
  454. sqlite3_finalize(query);
  455. m_mAccessMutex.unlock();
  456. return RetVal;
  457. };
  458. RetVal = sqlite3_last_insert_rowid(m_pDBLink);
  459. sqlite3_finalize(query);
  460. if (! m_bPersistentConnection)
  461. {
  462. if (! Disconnect())
  463. {
  464. m_mAccessMutex.unlock();
  465. return RetVal;
  466. };
  467. };
  468. m_mAccessMutex.unlock();
  469. if (RetVal == tVal)
  470. {
  471. RetVal = 0;
  472. }
  473. };
  474. return RetVal;
  475. }
  476. void SQLite_Connector::deleteResult(AAssoc *& R)
  477. {
  478. if (R)
  479. {
  480. while (R->size())
  481. {
  482. delete((Assoc *) R->at(0));
  483. R->erase(R->begin());
  484. };
  485. R->clear();
  486. delete(R);
  487. R = NULL;
  488. };
  489. }