log_db.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. #include <fstream>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <vector>
  5. #include <iterator>
  6. #include "log_db.h"
  7. #ifdef _WIN32
  8. #include <io.h>
  9. #include <direct.h>
  10. #include "atlbase.h"
  11. #endif //_WIN32
  12. #include "CMBSMDLL.h"
  13. #include "CppSQLite3.h"
  14. #include "inner_log.h"
  15. #include "log_util.h"
  16. #include <vector>
  17. #include <sys/stat.h>
  18. #include "zlib.h"
  19. #include "base64_openssl.h"
  20. #include <chrono>
  21. #include "baseFun.h"
  22. #include <log_producer_client.h>
  23. #ifndef _WIN32
  24. char* itoa(int value, char* buffer, int radix)
  25. {
  26. char* p;
  27. unsigned int a;
  28. //int len;
  29. char* b;
  30. char temp;
  31. unsigned int u;
  32. p = buffer;
  33. if (value < 0) {
  34. *p++ = '-';
  35. value = 0 - value;
  36. }
  37. u = (unsigned int)value;
  38. b = p;
  39. do {
  40. a = u % radix;
  41. u /= radix;
  42. *p++ = a + '0';
  43. } while (u > 0);
  44. //len = (int)(p-buffer);
  45. *p-- = 0;
  46. do {
  47. temp = *p;
  48. *p = *b;
  49. *b = temp;
  50. --p;
  51. ++b;
  52. } while (b < p);
  53. return buffer;
  54. }
  55. #endif // _WIN32
  56. #define MAX_CACHEDB_SIZE 500*1024*1024
  57. #define MIN_CACHEFREQUENCE_SIZE 50
  58. #define COMPRESS_CONTEXT
  59. const std::string COLUMN_ID = "id";
  60. const std::string COLUMN_DateTime = "date_time";
  61. const std::string COLUMN_Uuid = "uuid";
  62. const std::string COLUMN_Level = "level";
  63. const std::string COLUMN_Type = "type";
  64. const std::string COLUMN_Status = "status";
  65. const std::string COLUMN_Encrypt = "encrypt";
  66. const std::string COLUMN_Content = "content";
  67. int db_move_to_main(log_db_manager* manager);
  68. struct _log_db_manager {
  69. log_producer_config* config;
  70. CppSQLite3DB *db;
  71. std::string file_path;
  72. std::string file_name;
  73. std::string table_name;
  74. };
  75. log_db_manager* create_log_db(log_producer_config* config, char* base_path, char* file_name, char* table_name) {
  76. std::string str_file_name, dstFile;
  77. if (base_path == NULL || table_name == NULL || file_name == NULL) {
  78. aos_debug_log((LB, "create log db failed for null"));
  79. return NULL;
  80. }
  81. auto getFileSize = [](const char* fileName) -> int {
  82. if (fileName == NULL) {
  83. return -1;
  84. }
  85. struct stat statbuf;
  86. if (stat(fileName, &statbuf) == -1)
  87. return -1;
  88. // 获取文件大小
  89. size_t filesize = statbuf.st_size;
  90. return filesize;
  91. };
  92. auto IsFileOutDate = [](const char* fileName) -> bool
  93. {
  94. if (fileName == NULL) {
  95. return false;
  96. }
  97. struct stat statbuf;
  98. if (stat(fileName, &statbuf) == -1)
  99. return false;
  100. auto modifyTime = statbuf.st_mtime;
  101. auto curTime = time(nullptr);
  102. return (curTime - modifyTime) > 3600 * 72;//3 days
  103. };
  104. dstFile = std::string(base_path) + std::string(file_name);
  105. auto curFileSize = getFileSize(dstFile.c_str());
  106. const int MAX_DB_SIZE = 50 * 1024 * 1024;
  107. if (IsFileOutDate(dstFile.c_str()) || curFileSize > MAX_DB_SIZE) {
  108. #if defined(_MSC_VER)
  109. DeleteFile(dstFile.c_str());
  110. #else
  111. int status;
  112. status = unlink(dstFile.c_str());
  113. #endif //_MSC_VER
  114. }
  115. log_db_manager*log_db = new log_db_manager();
  116. log_db->file_path = base_path;
  117. str_file_name = file_name;
  118. log_db->file_name = str_file_name;
  119. log_db->table_name = table_name;
  120. log_db->db = new CppSQLite3DB();
  121. log_db->config = config;
  122. aos_debug_log((LB, "create log db success, db file_path %s, file_name %s, table_name %s",
  123. log_db->file_path.c_str(), log_db->file_name.c_str(), log_db->table_name.c_str()));
  124. return log_db;
  125. }
  126. void destroy_log_db(log_db_manager* manager) {
  127. if (manager != NULL) {
  128. if (manager != NULL) {
  129. try {
  130. if (manager->db)
  131. {
  132. manager->db->close();
  133. delete manager->db;
  134. manager->db = NULL;
  135. }
  136. }
  137. catch (...) {
  138. aos_error_log((LB, "close log db name %s failed.", manager->file_name.c_str()));
  139. }
  140. }
  141. aos_debug_log((LB, "destroy log db %s", manager->file_name.c_str()));
  142. delete manager;
  143. manager = NULL;
  144. }
  145. }
  146. bool createFile(std::string fileName) {
  147. std::fstream file;
  148. file.open(fileName, std::ios::out);
  149. if (!file) {
  150. return false;
  151. }
  152. file.close();
  153. return true;
  154. }
  155. int open_db(log_db_manager * manager) {
  156. if (manager == NULL || manager->db == NULL) {
  157. aos_error_log((LB, "open log db %s failed for null.", manager->file_name.c_str()));
  158. return false;
  159. }
  160. bool ret = true;
  161. try {
  162. std::string full_file_name;
  163. int mk_ret = mkdir_foreach((char*)manager->file_path.c_str(), manager->file_path.length());
  164. if (mk_ret < 0){
  165. aos_error_log((LB, "make log db %s file path failed.", manager->file_name.c_str()));
  166. return false;
  167. }
  168. full_file_name = manager->file_path + manager->file_name;
  169. char* name = (char*)full_file_name.c_str();
  170. manager->db->open(name);
  171. if (!db_is_exist_table_ex(manager, (char *)manager->table_name.c_str())) {
  172. std::string strCreateTable = "CREATE TABLE IF NOT EXISTS ";
  173. strCreateTable.append(manager->table_name).append(" (" +
  174. //COLUMN_ID + " INTEGER DEFAULT '1' NOT NULL PRIMARY KEY AUTOINCREMENT," +
  175. COLUMN_DateTime + " INTEGER," +
  176. COLUMN_Uuid + " TEXT NOT NULL PRIMARY KEY," +
  177. COLUMN_Level + " INTEGER," +
  178. COLUMN_Type + " INTEGER," +
  179. COLUMN_Status + " INTEGER DEFAULT 0," +
  180. COLUMN_Encrypt + " INTEGER DEFAULT 0," +
  181. COLUMN_Content + " TEXT" +
  182. ");");
  183. int CTRet = manager->db->execDML(strCreateTable.c_str());
  184. //aos_debug_log((LB, "create log table result %d, db name %s", CTRet, name));
  185. }
  186. //manager->db->execDML("PRAGMA synchronous = FULL;");
  187. }
  188. catch (CppSQLite3Exception& e)
  189. {
  190. aos_error_log((LB, "open log db %s error %s", manager->file_name.c_str(), e.errorMessage()));
  191. if (manager->db != NULL) {
  192. try {
  193. manager->db->close();
  194. }
  195. catch (...) {
  196. aos_error_log((LB, "close log db %s failed.", manager->file_name.c_str()));
  197. }
  198. delete manager->db;
  199. manager->db = NULL;
  200. }
  201. ret = false;
  202. }
  203. return ret;
  204. }
  205. void close_logdb(log_db_manager* manager)
  206. {
  207. if (manager!= NULL && manager->db != NULL) {
  208. try {
  209. manager->db->close();
  210. }
  211. catch (...) {
  212. aos_error_log((LB, "close log db %s failed.", manager->file_name.c_str()));
  213. }
  214. delete manager->db;
  215. manager->db = NULL;
  216. }
  217. }
  218. int drop_db(log_db_manager* manager)
  219. {
  220. if (manager == NULL || manager->db == NULL) {
  221. aos_error_log((LB, "drop log db %s failed for null.", manager->file_name.c_str()));
  222. return false;
  223. }
  224. bool ret = true;
  225. try {
  226. std::string strSql = "DROP TABLE IF EXISTS ";
  227. strSql.append(manager->table_name);
  228. int CTRet = manager->db->execDML(strSql.c_str());
  229. aos_debug_log((LB, "drop log db %s result %d table name %s", manager->file_name.c_str(), CTRet, manager->table_name.c_str()));
  230. }
  231. catch (CppSQLite3Exception& e)
  232. {
  233. aos_error_log((LB, "drop log db %s error %s", manager->file_name.c_str(), e.errorMessage()));
  234. ret = false;
  235. }
  236. return ret;
  237. }
  238. int db_insert_group(log_db_manager* manager, log_group_builder* builder) {
  239. if (manager == NULL || manager->db == NULL) {
  240. aos_error_log((LB, "insert log db %s failed for null.", manager->file_name.c_str()));
  241. return false;
  242. }
  243. int ret = true;
  244. serialize_buf buf;
  245. for (int i = 0; i < builder->grp->n_logs; i++) {
  246. memset(&buf, 0, sizeof(serialize_buf));
  247. serialize_to_buf(&builder->grp->logs[i], &buf);
  248. ret = db_insert_one(manager, &buf);
  249. }
  250. return ret;
  251. }
  252. int db_insert_one(log_db_manager* manager, serialize_buf* buf) {
  253. if (manager == NULL || manager->db == NULL) {
  254. aos_error_log((LB, "insert log db %s failed for null.", manager->file_name.c_str()));
  255. return false;
  256. }
  257. int ret = true;
  258. std::string strSql = "insert into ";
  259. long time = LOG_GET_TIME();
  260. char strTime[128];
  261. char strLevel[32];
  262. char strType[32];
  263. char strEncrypt[32];
  264. sprintf(strTime, "%ld", time);
  265. sprintf(strLevel, "%d", buf->level);
  266. sprintf(strType, "%d", buf->type);
  267. sprintf(strEncrypt, "%d", manager->config->usePersistentEncrypt);
  268. unsigned long end_time;
  269. unsigned long start_time = GetTickCount();
  270. //SM4加密,密文会比明文长16字节
  271. if (manager->config->usePersistentEncrypt == 1) {
  272. int input_length = strlen(buf->buffer) + 1;
  273. unsigned char* input_data = (unsigned char*)buf->buffer;
  274. int output_length = input_length + 16;
  275. unsigned char* output_data = (unsigned char*)malloc(output_length);
  276. CMBSM4EncryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword, input_data, input_length, output_data, &output_length);
  277. char* output_str_data = (char*)malloc(output_length * 2 + 1);
  278. memset(output_str_data, 0, output_length * 2 + 1);
  279. convertUnCharTotr(output_str_data, output_data, output_length);
  280. strSql.append(manager->table_name).append("(" + COLUMN_DateTime +
  281. "," + COLUMN_Uuid + "," + COLUMN_Level + "," + COLUMN_Type + "," + COLUMN_Content + "," + COLUMN_Encrypt + "," + COLUMN_Status +
  282. ") VALUES (").append(strTime).append(",'").append(buf->uuid).append("',").
  283. append(strLevel).append(",").append(strType).append(",'").
  284. append(output_str_data).append("',").append(strEncrypt).append(",0)");
  285. free(output_data);
  286. free(output_str_data);
  287. end_time = GetTickCount();
  288. //aos_debug_log((LB, "db_insert_one Encrypt cust %d", end_time - start_time));
  289. }
  290. else if(manager->config->usePersistentEncrypt == 2)
  291. {
  292. int input_length = strlen(buf->buffer) + 1;
  293. unsigned char* input_data = (unsigned char*)buf->buffer;
  294. unsigned long compressLen = input_length * 2 + 1;
  295. unsigned char* compress_str_data = (unsigned char*)malloc(compressLen);
  296. memset(compress_str_data, 0, compressLen);
  297. compress(compress_str_data, &compressLen, (unsigned char*)input_data, input_length);
  298. int output_length = compressLen + 16;
  299. unsigned char* output_data = (unsigned char*)malloc(output_length);
  300. CMBSM4EncryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword, compress_str_data, compressLen, output_data, &output_length);
  301. char* output_str_data = openssl_base64_encode((char*)output_data, output_length);
  302. //try to decrypt
  303. /*
  304. char* input_str_data = output_str_data;
  305. char* decoded_bytes = NULL;
  306. size_t decoded_length = 0;
  307. openssl_base64_decode(input_str_data, &decoded_bytes, &decoded_length);
  308. int SM4_length = decoded_length;
  309. char* SM4_data = (char*)malloc(decoded_length);
  310. memset(SM4_data, 0, decoded_length);
  311. CMBSM4DecryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword,
  312. (unsigned char*)decoded_bytes, decoded_length, (unsigned char*)SM4_data, &SM4_length);
  313. uLongf uncompress_length = SM4_length * 3;
  314. char *output_data2 = (char*)malloc(uncompress_length);
  315. memset(output_data2, 0, uncompress_length);
  316. uncompress((unsigned char*)output_data2, &uncompress_length, (unsigned char*)SM4_data, SM4_length);
  317. if(SM4_data)
  318. free(SM4_data);
  319. if(decoded_bytes)
  320. free(decoded_bytes);
  321. */
  322. strSql.append(manager->table_name).append("(" + COLUMN_DateTime +
  323. "," + COLUMN_Uuid + "," + COLUMN_Level + "," + COLUMN_Type + "," + COLUMN_Content + "," + COLUMN_Encrypt + "," + COLUMN_Status +
  324. ") VALUES (").append(strTime).append(",'").append(buf->uuid).append("',").
  325. append(strLevel).append(",").append(strType).append(",'").
  326. append((char*)output_str_data).append("',").append(strEncrypt).append(",0)");
  327. if(compress_str_data)
  328. free(compress_str_data);
  329. if(output_data)
  330. free(output_data);
  331. if(output_str_data)
  332. free(output_str_data);
  333. end_time = GetTickCount();
  334. }
  335. else if (manager->config->usePersistentEncrypt == 3)
  336. {
  337. if (strlen(buf->buffer) == 0)
  338. return ret;
  339. int input_length = strlen(buf->buffer) + 1;
  340. unsigned char* input_data = (unsigned char*)buf->buffer;
  341. int output_length = input_length + 16;
  342. unsigned char* output_data = (unsigned char*)malloc(output_length);
  343. CMBSM4EncryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword, input_data, input_length, output_data, &output_length);
  344. char* output_str_data = openssl_base64_encode((char*)output_data, output_length);
  345. //try to decrypt
  346. /*
  347. char* input_str_data = output_str_data;
  348. char* decoded_bytes = NULL;
  349. size_t decoded_length = 0;
  350. openssl_base64_decode(input_str_data, &decoded_bytes, &decoded_length);
  351. int SM4_length = decoded_length;
  352. char* SM4_data = (char*)malloc(decoded_length);
  353. memset(SM4_data, 0, decoded_length);
  354. CMBSM4DecryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword,
  355. (unsigned char*)decoded_bytes, decoded_length, (unsigned char*)SM4_data, &SM4_length);
  356. //RvcLogSdkManager::getInstance().SendTestLog(output_str_data);
  357. if(SM4_data)
  358. free(SM4_data);
  359. if(decoded_bytes)
  360. free(decoded_bytes);
  361. */
  362. /*
  363. if (buf->type == LOG_TYPE_BEIDOU)
  364. {
  365. std::string dstLog = std::string(buf->uuid) + " db_insert_one_beidou encrypt3";
  366. log_producer_sendTestLog_loki("RVCLogSDK", buf->uuid, dstLog.c_str());
  367. }
  368. else
  369. {
  370. std::string dstLog = std::string(buf->uuid) + " db_insert_one_skyeye encrypt3";
  371. log_producer_sendTestLog_loki("RVCLogSDK", buf->uuid, dstLog.c_str());
  372. }
  373. */
  374. strSql.append(manager->table_name).append("(" + COLUMN_DateTime +
  375. "," + COLUMN_Uuid + "," + COLUMN_Level + "," + COLUMN_Type + "," + COLUMN_Content + "," + COLUMN_Encrypt + "," + COLUMN_Status +
  376. ") VALUES (").append(strTime).append(",'").append(buf->uuid).append("',").
  377. append(strLevel).append(",").append(strType).append(",'").
  378. append((char*)output_str_data).append("',").append(strEncrypt).append(",0)");
  379. if (output_data)
  380. free(output_data);
  381. if (output_str_data)
  382. free(output_str_data);
  383. end_time = GetTickCount();
  384. }
  385. else {
  386. #ifdef COMPRESS_CONTEXT
  387. unsigned char dstBuf[10000] = "";
  388. unsigned long len = 10000;
  389. compress(dstBuf, &len, (unsigned char*)buf->buffer, buf->buffer_len);
  390. strSql.append(manager->table_name).append("(" + COLUMN_DateTime +
  391. "," + COLUMN_Uuid + "," + COLUMN_Level + "," + COLUMN_Type + "," + COLUMN_Content + "," + COLUMN_Encrypt + "," + COLUMN_Status +
  392. ") VALUES (").append(strTime).append(",'").append(buf->uuid).append("',").
  393. append(strLevel).append(",").append(strType).append(",'").
  394. append((char*)dstBuf).append("',").append(strEncrypt).append(",0)");
  395. #else
  396. strSql.append(manager->table_name).append("(" + COLUMN_DateTime +
  397. "," + COLUMN_Uuid + "," + COLUMN_Level + "," + COLUMN_Type + "," + COLUMN_Content + "," + COLUMN_Encrypt + "," + COLUMN_Status +
  398. ") VALUES (").append(strTime).append(",'").append(buf->uuid).append("',").
  399. append(strLevel).append(",").append(strType).append(",'").
  400. append((char*)buf->buffer).append("',").append(strEncrypt).append(",0)");
  401. #endif
  402. }
  403. try {
  404. int CTRet = manager->db->execDML(strSql.c_str());
  405. end_time = GetTickCount();
  406. //aos_debug_log((LB, "db_insert_one execDML cust %d", end_time - start_time));
  407. //aos_debug_log((LB, "db %s insert one log result %d, log uuid %s", manager->file_name.c_str(), CTRet, buf->uuid));
  408. }
  409. catch (CppSQLite3Exception& e)
  410. {
  411. aos_error_log((LB, "db %s insert one log error %s, log uuid %s", manager->file_name.c_str(), e.errorMessage(), buf->uuid));
  412. ret = false;
  413. }
  414. return ret;
  415. }
  416. int getReadType()
  417. {
  418. static unsigned int sum = 0;
  419. sum = sum % 100;
  420. sum++;
  421. int cmpData = sum % 11;
  422. if (cmpData <= 5)
  423. return build_type_e::LOG_TYPE_SYS_SKYEYE;
  424. else if (cmpData <= 6)
  425. return build_type_e::LOG_TYPE_BEIDOU;
  426. else if (cmpData <= 7)
  427. return build_type_e::LOG_TYPE_USER_SKYEYE;
  428. else if (cmpData <= 8)
  429. return build_type_e::LOG_TYPE_USER_BUSINESS;
  430. else if (cmpData <= 9)
  431. return build_type_e::LOG_TYPE_SYS_BUSINESS;
  432. else if (cmpData <= 10)
  433. return build_type_e::LOG_TYPE_WEBSDK;
  434. else
  435. return 1;
  436. }
  437. log_group_builder* db_read_table_last_logs(log_db_manager* manager, int count) {
  438. if (manager == NULL || manager->db == NULL) {
  439. aos_error_log((LB, "read last logs db %s failed for null.", manager->file_name.c_str()));
  440. return NULL;
  441. }
  442. build_item log;
  443. char strStatus[32];
  444. char strCount[32];
  445. log_group_builder* builder = log_group_create(manager->config);
  446. sprintf(strStatus, "%d", LOG_DB_STATUS_SENDING);
  447. sprintf(strCount, "%d", count);
  448. std::string querySql = "select * from ";
  449. querySql.append(manager->table_name);
  450. int readType = getReadType();
  451. querySql.append(" where " + COLUMN_Status + " != ").append(strStatus).append(" AND ").append(COLUMN_Type).append("=").append(std::to_string((long long)readType));
  452. querySql.append(/*" order by " + COLUMN_DateTime + */" LIMIT ").append(strCount).append(";");
  453. try {
  454. CppSQLite3Query q = manager->db->execQuery(querySql.c_str());
  455. if (q.eof())
  456. {
  457. //if can not find, try to get LOG_TYPE_SYS_SKYEYE logs
  458. std::string searchSys= "select * from ";
  459. searchSys.append(manager->table_name);
  460. searchSys.append(" where " + COLUMN_Status + " != ").append(strStatus);
  461. searchSys.append(/*" order by " + COLUMN_DateTime + */" LIMIT ").append(strCount).append(";");
  462. q = manager->db->execQuery(searchSys.c_str());
  463. }
  464. while (!q.eof()) {
  465. int encrypt = q.getIntField(COLUMN_Encrypt.c_str(), 0);
  466. log.type = (build_type_e)q.getIntField(COLUMN_Type.c_str(), LOG_TYPE_USER_SKYEYE);
  467. //只获取同一类型的日志
  468. if (builder->grp->n_logs != 0 && builder->grp->logs[0].type != log.type) {
  469. q.nextRow();
  470. continue;
  471. }
  472. strcpy(log.uuid, q.getStringField(COLUMN_Uuid.c_str()));
  473. log.level = (LOG_LEVEL_E)q.getIntField(COLUMN_Level.c_str(), LOG_LEVEL_DEBUG);
  474. //content
  475. char* output_data = NULL;
  476. if (encrypt == 1) {
  477. char* input_str_data = (char*)q.getStringField(COLUMN_Content.c_str());
  478. int input_length = strlen(input_str_data) / 2;
  479. unsigned char* input_data = (unsigned char*)malloc(input_length);
  480. memset(input_data, 0, input_length);
  481. convertStrToUnChar(input_str_data, input_data);
  482. int output_length = input_length;
  483. output_data = (char*)malloc(input_length);
  484. memset(output_data, 0, input_length);
  485. CMBSM4DecryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword,
  486. input_data, input_length, (unsigned char*)output_data, &output_length);
  487. log.buffer = output_data;
  488. log.buffer_len = strlen(log.buffer) + 1;
  489. add_log_raw(builder, &log);
  490. free(input_data);
  491. }
  492. else if (encrypt == 2) {
  493. char* input_str_data = (char*)q.getStringField(COLUMN_Content.c_str());
  494. char* decoded_bytes = NULL;
  495. size_t decoded_length = 0;
  496. openssl_base64_decode(input_str_data, &decoded_bytes, &decoded_length);
  497. int SM4_length = decoded_length;
  498. char *SM4_data = (char*)malloc(decoded_length);
  499. memset(SM4_data, 0, decoded_length);
  500. CMBSM4DecryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword,
  501. (unsigned char*)decoded_bytes, decoded_length, (unsigned char*)SM4_data, &SM4_length);
  502. uLongf uncompress_length = SM4_length * 3;
  503. output_data = (char*)malloc(uncompress_length);
  504. memset(output_data, 0, uncompress_length);
  505. uncompress((unsigned char*)output_data, &uncompress_length, (unsigned char*)SM4_data, SM4_length);
  506. log.buffer = (char*)output_data;
  507. log.buffer_len = strlen(log.buffer) + 1;
  508. add_log_raw(builder, &log);
  509. free(SM4_data);
  510. free(decoded_bytes);
  511. }
  512. else if (encrypt == 3) {
  513. char* input_str_data = (char*)q.getStringField(COLUMN_Content.c_str());
  514. char* decoded_bytes = NULL;
  515. size_t decoded_length = 0;
  516. openssl_base64_decode(input_str_data, &decoded_bytes, &decoded_length);
  517. int SM4_length = decoded_length;
  518. char* SM4_data = (char*)malloc(decoded_length);
  519. memset(SM4_data, 0, decoded_length);
  520. CMBSM4DecryptWithECB((unsigned char*)manager->config->PersistentEncryptPassword,
  521. (unsigned char*)decoded_bytes, decoded_length, (unsigned char*)SM4_data, &SM4_length);
  522. log.buffer = (char*)SM4_data;
  523. log.buffer_len = strlen(log.buffer) + 1;
  524. add_log_raw(builder, &log);
  525. free(SM4_data);
  526. free(decoded_bytes);
  527. }
  528. else {
  529. std::string src = (char*)q.getStringField(COLUMN_Content.c_str());
  530. #ifdef COMPRESS_CONTEXT
  531. unsigned char dst[10000] = "";
  532. uLongf dstLen = 10000;
  533. uncompress(dst, &dstLen, (unsigned char*)src.c_str(), src.length());
  534. log.buffer = (char*)dst;
  535. log.buffer_len = dstLen + 1;
  536. #else
  537. log.buffer = (char*)q.getStringField(COLUMN_Content.c_str());
  538. log.buffer_len = strlen(log.buffer) + 1;
  539. #endif // COMPRESS_CONTEXT
  540. add_log_raw(builder, &log);
  541. }
  542. strcpy(builder->modular, manager->file_name.c_str());
  543. if (output_data != NULL) {
  544. free(output_data);
  545. }
  546. //aos_debug_log((LB, "read last log db %s, uuid %s.", manager->file_name.c_str(), log.uuid));
  547. q.nextRow();
  548. }
  549. q.finalize();
  550. }
  551. catch (CppSQLite3Exception& e)
  552. {
  553. aos_error_log((LB, "db %s read logs error %s, querySql %s", manager->file_name.c_str(), e.errorMessage(), querySql.c_str()));
  554. log_group_destroy(builder);
  555. return NULL;
  556. }
  557. if (builder->grp->n_logs == 0) {
  558. log_group_destroy(builder);
  559. return NULL;
  560. }
  561. return builder;
  562. }
  563. int db_delete_old_logs(log_db_manager* manager, int count) {
  564. if (manager == NULL || manager->db == NULL) {
  565. aos_error_log((LB, "delete old logs db %s failed for null.", manager->file_name.c_str()));
  566. return false;
  567. }
  568. int ret = true;
  569. char strCount[64];
  570. itoa(count, strCount, 10);
  571. std::string sql = "delete from ";
  572. sql.append(manager->table_name);
  573. sql.append(" where "+ COLUMN_Uuid + " in (select " + COLUMN_Uuid + " from "+ manager->table_name +" order by " + COLUMN_DateTime + " ASC LIMIT " + strCount+")");
  574. sql.append(";");
  575. try {
  576. int CTRet = manager->db->execDML(sql.c_str());
  577. aos_debug_log((LB, "db %s delete old log result %d table name %s", manager->file_name.c_str(), CTRet, manager->table_name.c_str()));
  578. }
  579. catch (CppSQLite3Exception& e)
  580. {
  581. aos_error_log((LB, "db %s delete old log error %s", manager->file_name.c_str(), e.errorMessage()));
  582. ret = false;
  583. }
  584. return ret;
  585. }
  586. int db_delete_one(log_db_manager* manager, char* uuid) {
  587. if (manager == NULL || manager->db == NULL) {
  588. aos_error_log((LB, "delete one log db %s failed for null.", manager->file_name.c_str()));
  589. return false;
  590. }
  591. int ret = true;
  592. std::string sql = "delete from ";
  593. sql.append(manager->table_name);
  594. sql.append(" where "+ COLUMN_Uuid + " = '").append(uuid).append("';");
  595. try {
  596. int CTRet = manager->db->execDML(sql.c_str());
  597. /*
  598. aos_debug_log((LB, "db %s delete one uuid:%s log result %d", manager->file_name.c_str(), uuid, CTRet));
  599. if (CTRet != 1)
  600. MessageBox(NULL, NULL, NULL, 0);
  601. */
  602. }
  603. catch (CppSQLite3Exception& e)
  604. {
  605. aos_error_log((LB, "db %s delete one log error %s, log uuid %s", manager->file_name.c_str(), e.errorMessage(), uuid));
  606. ret = false;
  607. }
  608. return ret;
  609. }
  610. #if defined(_WIN32)
  611. #include <windows.h>
  612. #else
  613. #include <dirent.h>
  614. #include <cstring>
  615. #endif
  616. #include <winpr/file.h>
  617. #include <uuid4.h>
  618. #include <winpr/library.h>
  619. #include "../libtoolkit/path.h"
  620. std::vector<std::string> scan_db_files(const std::string& directory) {
  621. std::vector<std::string> db_files;
  622. #if defined(_WIN32)
  623. std::string search_path = directory + "/RvcLogSdk_*.db";
  624. WIN32_FIND_DATA find_file_data;
  625. HANDLE hFind = FindFirstFile(search_path.c_str(), &find_file_data);
  626. if (hFind == INVALID_HANDLE_VALUE) {
  627. std::cerr << "No files found." << std::endl;
  628. }
  629. else {
  630. do {
  631. std::string filename = find_file_data.cFileName;
  632. if (filename.size() > 3 && filename.substr(filename.size() - 3) == ".db") {
  633. db_files.push_back(directory + "/" + filename);
  634. }
  635. } while (FindNextFile(hFind, &find_file_data) != 0);
  636. FindClose(hFind);
  637. }
  638. #else
  639. DIR* dir = opendir(directory.c_str());
  640. if (dir != nullptr) {
  641. struct dirent* entry;
  642. while ((entry = readdir(dir)) != nullptr) {
  643. std::string filename = entry->d_name;
  644. if (filename.rfind("RvcLogSdk_", 0) == 0 && filename.size() > 3 && filename.substr(filename.size() - 3) == ".db") {
  645. db_files.push_back(directory + "/" + filename);
  646. }
  647. }
  648. closedir(dir);
  649. }
  650. else {
  651. std::cerr << "Failed to open directory." << std::endl;
  652. }
  653. #endif
  654. return db_files;
  655. }
  656. int db_get_count(log_db_manager* manager) {
  657. static auto start_time = std::chrono::high_resolution_clock::now();
  658. if (manager == NULL || manager->db == NULL) {
  659. aos_error_log((LB, "get db %s count failed for null.", manager->file_name.c_str()));
  660. return 0;
  661. }
  662. int ret = 0;
  663. std::string sql = "select count(";
  664. sql.append(COLUMN_Uuid).append(") from ");
  665. sql.append(manager->table_name);
  666. try {
  667. ret = manager->db->execScalar(sql.c_str());
  668. g_notUploadLogNum = ret;
  669. //aos_debug_log((LB, "db %s get count %d", manager->file_name.c_str(), ret));
  670. }
  671. catch (CppSQLite3Exception& e)
  672. {
  673. aos_error_log((LB, "get db %s count error %s", manager->file_name.c_str(), e.errorMessage()));
  674. ret = 0;
  675. }
  676. auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::high_resolution_clock::now() - start_time);
  677. if (elapsed_time.count() > 120 && ret < 500)
  678. {
  679. db_move_to_main(manager);
  680. start_time = std::chrono::high_resolution_clock::now();
  681. }
  682. return ret;
  683. }
  684. int db_move_to_main(log_db_manager* manager)
  685. {
  686. if (manager == NULL || manager->db == NULL) {
  687. aos_error_log((LB, "db_move_to_main get db %s count failed for null.", manager->file_name.c_str()));
  688. return 0;
  689. }
  690. char tmp[MAX_PATH];
  691. GetModuleFileNameA(NULL, tmp, MAX_PATH);
  692. *strrchr(tmp, SPLIT_SLASH) = 0;
  693. *strrchr(tmp, SPLIT_SLASH) = 0;
  694. *strrchr(tmp, SPLIT_SLASH) = 0;
  695. *strrchr(tmp, SPLIT_SLASH) = 0;
  696. *strrchr(tmp, SPLIT_SLASH) = 0;
  697. sprintf(tmp, "%s" SPLIT_SLASH_STR "rvc" SPLIT_SLASH_STR "terminaldbstorage" SPLIT_SLASH_STR "RVC.LogSdk", tmp);
  698. auto db_files = scan_db_files(tmp);
  699. if (db_files.size() == 0)
  700. return 0;
  701. auto uuidStr = "sql"+uuid4_generate(8);
  702. int ret = true;
  703. char *zSql = sqlite3_mprintf(
  704. "ATTACH DATABASE \"%s\" AS %s;\n"
  705. "INSERT OR IGNORE INTO RvcLogTable SELECT * FROM %s.RvcLogTable;\n"
  706. "DELETE FROM %s.RvcLogTable;\n"
  707. "DETACH DATABASE %s;\n",
  708. db_files[0].c_str(), uuidStr.c_str(), uuidStr.c_str(), uuidStr.c_str(), uuidStr.c_str()
  709. );
  710. std::string sqlStr = zSql;
  711. sqlite3_free(zSql);
  712. try {
  713. ret = manager->db->execDML(sqlStr.c_str()); // if failed, it will throw exception
  714. DeleteFile(db_files[0].c_str());
  715. }
  716. catch (CppSQLite3Exception& e)
  717. {
  718. ret = false;
  719. }
  720. return ret;
  721. }
  722. int db_update_status(log_db_manager* manager, char* uuid, log_db_status_e status) {
  723. if (manager == NULL || manager->db == NULL) {
  724. aos_error_log((LB, "db %s update log status failed for null.", manager->file_name.c_str()));
  725. return false;
  726. }
  727. int ret = true;
  728. char strStatus[32];
  729. char strSendingStatus[32];
  730. sprintf(strSendingStatus, "%d", LOG_DB_STATUS_SENDING);
  731. sprintf(strStatus, "%d", status);
  732. std::string sql = "update ";
  733. sql.append(manager->table_name);
  734. sql.append(" set " + COLUMN_Status + " = ").append(strStatus);
  735. if (uuid == NULL) {
  736. //sql.append(";");
  737. sql.append(" where " + COLUMN_Status + " = ").append(strSendingStatus).append(";");
  738. }
  739. else {
  740. sql.append(" where " + COLUMN_Uuid + " = '").append(uuid).append("';");
  741. }
  742. try {
  743. int CTRet = manager->db->execDML(sql.c_str());
  744. //aos_debug_log((LB, "db %s update one uuid:%s status:%d log result %d", manager->file_name.c_str(), uuid, status, CTRet));
  745. }
  746. catch (CppSQLite3Exception& e)
  747. {
  748. aos_error_log((LB, "db %s update one log error %s, log uuid %s", manager->file_name.c_str(), e.errorMessage(), uuid));
  749. ret = false;
  750. }
  751. return ret;
  752. }
  753. int db_is_exist_table_ex(log_db_manager* manager, char* tablename){
  754. if (manager == NULL || manager->db == NULL) {
  755. aos_error_log((LB, "db %s is exist table ex failed for null.", manager->file_name.c_str()));
  756. return false;
  757. }
  758. std::string beginStr = "select count(*) from sqlite_master where type ='table' and name='";
  759. std::string queryStr = beginStr.append(tablename).append("';");
  760. try {
  761. int Ret = 0;
  762. Ret = manager->db->execScalar(queryStr.c_str());
  763. if( 0 == Ret)
  764. return false;
  765. }
  766. catch (CppSQLite3Exception& e)
  767. {
  768. aos_error_log((LB, "db %s update one log error %s", manager->file_name.c_str(), e.errorMessage()));
  769. return false;
  770. }
  771. return true;
  772. }
  773. int db_get_tables(log_db_manager* manager, char** tables, int* table_count) {
  774. if (manager == NULL || manager->db == NULL) {
  775. aos_error_log((LB, "db %s get table names failed for null.", manager->file_name.c_str()));
  776. return false;
  777. }
  778. std::vector<std::string> table_vec;
  779. std::string queryStr = "select name from sqlite_master where type ='table' and name NOT LIKE 'sqlite_%'";
  780. try {
  781. CppSQLite3Query q = manager->db->execQuery(queryStr.c_str());
  782. while (!q.eof()) {
  783. char* table_name = (char*)q.getStringField("name");
  784. table_vec.insert(table_vec.begin(), table_name);
  785. q.nextRow();
  786. }
  787. q.finalize();
  788. *table_count = table_vec.size();
  789. tables = (char **)malloc(*table_count * sizeof(char *));
  790. for (int i = 0; i < *table_count; i++) {
  791. int len = table_vec[i].length();
  792. tables[i] = (char *)malloc(len + 1);
  793. strcpy(tables[i], table_vec[i].c_str());
  794. }
  795. }
  796. catch (CppSQLite3Exception& e)
  797. {
  798. aos_error_log((LB, "db %s get table names error %s", manager->file_name.c_str(), e.errorMessage()));
  799. return false;
  800. }
  801. return true;
  802. }
  803. int db_vacuum(log_db_manager* manager){
  804. int CTRet;
  805. try {
  806. CTRet = manager->db->execDML("VACUUM");
  807. aos_debug_log((LB, "db %s exec VACUUM result %d", manager->file_name.c_str(), CTRet));
  808. }
  809. catch (CppSQLite3Exception& e)
  810. {
  811. aos_error_log((LB, "db %s exec VACUUM error %s", manager->file_name.c_str(), e.errorMessage()));
  812. return false;
  813. }
  814. return true;
  815. }
  816. int db_transaction_begin(log_db_manager* manager) {
  817. int CTRet;
  818. try {
  819. CTRet = manager->db->execDML("begin;");
  820. //aos_debug_log((LB, "db %s exec begin result %d", manager->file_name.c_str(), CTRet));
  821. }
  822. catch (CppSQLite3Exception& e)
  823. {
  824. aos_error_log((LB, "db %s exec begin error %s", manager->file_name.c_str(), e.errorMessage()));
  825. return false;
  826. }
  827. return true;
  828. }
  829. int db_transaction_commit(log_db_manager* manager) {
  830. int CTRet;
  831. try {
  832. CTRet = manager->db->execDML("commit;");
  833. //aos_debug_log((LB, "db %s exec commit result %d", manager->file_name.c_str(), CTRet));
  834. }
  835. catch (CppSQLite3Exception& e)
  836. {
  837. aos_error_log((LB, "db %s exec commit error %s", manager->file_name.c_str(), e.errorMessage()));
  838. return false;
  839. }
  840. return true;
  841. }