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.

1535 lines
31 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
23 hours ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "basicFunctionality.h"
  2. #include "../../alg/generic/md5.h"
  3. #include <sys/ioctl.h>
  4. // #include <sys/sendfile.h>
  5. #ifdef DEBUG
  6. #include "basicLogCollection.h"
  7. #define URGENT_LOG(X) basicLogCollection::getInstance()->Log("basic Functionality", NULL, X)
  8. #endif
  9. #ifdef __linux__
  10. int ch_chown(const char * file_path, const char * user_name, const char * group_name)
  11. {
  12. uid_t uid;
  13. gid_t gid;
  14. struct passwd * pwd;
  15. struct group * grp;
  16. pwd = getpwnam(user_name);
  17. if (pwd == NULL)
  18. {
  19. #ifdef DEBUG
  20. URGENT_LOG("Failed to get uid!");
  21. #endif
  22. return -1;
  23. };
  24. uid = pwd->pw_uid;
  25. grp = getgrnam(group_name);
  26. if (grp == NULL)
  27. {
  28. #ifdef DEBUG
  29. URGENT_LOG("Failed to get gid!");
  30. #endif
  31. return -1;
  32. };
  33. gid = grp->gr_gid;
  34. return chown(file_path, uid, gid);
  35. }
  36. #endif
  37. int getLocalDay(){
  38. time_t LocalTime;
  39. time(&LocalTime);
  40. tm local_time;
  41. tm * gmt_time = &local_time;
  42. if( localtime_r(&LocalTime, gmt_time) == NULL ){
  43. return -1;
  44. } else {
  45. return gmt_time->tm_mday;
  46. };
  47. }
  48. int getLocalHour(time_t t){
  49. if ( t == 0 ) t = time(NULL);
  50. tm local_time;
  51. if( localtime_r(&t, &local_time) == NULL ){
  52. return -1;
  53. };
  54. return local_time.tm_hour;
  55. }
  56. int checkCmdExists(CSTR cmd)
  57. {
  58. FILE * fd = popen(cmd, "r");
  59. char tB[1024];
  60. int rVal = -1;
  61. if (fd != NULL)
  62. {
  63. while (! feof(fd))
  64. {
  65. fgets((CSTR) tB, 1024, fd);
  66. trim(tB);
  67. if (strstr(tB, "command not found") != NULL)
  68. {
  69. rVal = 0;
  70. break;
  71. };
  72. };
  73. if (rVal < 1)
  74. {
  75. rVal = 1;
  76. }
  77. fclose(fd);
  78. };
  79. return rVal;
  80. }
  81. uid_t getUserUid(CSTR uname)
  82. {
  83. struct passwd * pwd;
  84. if (uname == NULL)
  85. {
  86. return -1;
  87. }
  88. pwd = getpwnam(uname); /* Try getting UID for username */
  89. if (pwd == NULL)
  90. {
  91. return -1;
  92. }
  93. return pwd->pw_uid;
  94. }
  95. gid_t getUserGid(CSTR uname)
  96. {
  97. struct passwd * pwd;
  98. if (uname == NULL)
  99. {
  100. return -1;
  101. }
  102. pwd = getpwnam(uname); /* Try getting GID for username */
  103. if (pwd == NULL)
  104. {
  105. return -1;
  106. }
  107. return pwd->pw_gid;
  108. }
  109. bool createAccessibleDir(CSTR path, mode_t mode, uid_t uid, gid_t gid)
  110. {
  111. if (mkdir(path, mode) != 0)
  112. {
  113. return false;
  114. }
  115. chown(path, uid, gid);
  116. return true;
  117. }
  118. #ifdef __linux__
  119. int fileCopy(const char * source, const char * destination)
  120. {
  121. int input, output;
  122. if ((input = open(source, O_RDONLY)) == -1)
  123. {
  124. return -1;
  125. }
  126. if ((output = creat(destination, 0660)) == -1)
  127. {
  128. close(input);
  129. return -1;
  130. };
  131. // Here we use kernel-space copying for performance reasons
  132. #if defined(__APPLE__) || defined(__FreeBSD__)
  133. // fcopyfile works on FreeBSD and OS X 10.5+
  134. int result = fcopyfile(input, output, 0, COPYFILE_ALL);
  135. #else
  136. // sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
  137. off_t bytesCopied = 0;
  138. struct stat fileinfo = {};
  139. fstat(input, &fileinfo);
  140. int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
  141. #endif
  142. close(input);
  143. close(output);
  144. return result;
  145. }
  146. #endif
  147. bool fileExist(CSTR strFilename)
  148. {
  149. struct stat stFileInfo;
  150. int intStat;
  151. intStat = stat(strFilename, &stFileInfo);
  152. if (intStat == 0)
  153. {
  154. return true;
  155. };
  156. return false;
  157. }
  158. bool dirEmpty(CSTR dirname)
  159. {
  160. int n = 0;
  161. struct dirent * d;
  162. DIR * dir = opendir(dirname);
  163. if (dir == NULL)
  164. {
  165. return true;
  166. }
  167. while ((d = readdir(dir)) != NULL)
  168. {
  169. if (++n > 2)
  170. {
  171. break;
  172. }
  173. }
  174. closedir(dir);
  175. if (n <= 2)
  176. {
  177. return true;
  178. }
  179. return false;
  180. }
  181. #ifndef __linux__
  182. #else
  183. #include <sys/syscall.h>
  184. #include <sys/types.h>
  185. #include <unistd.h>
  186. pid_t gettid(void)
  187. {
  188. return syscall(SYS_gettid);
  189. }
  190. #endif
  191. const char * __BuildDate = (__DATE__);
  192. const char * __BuildTime = (__TIME__);
  193. const char * __BuildTS = (__TIMESTAMP__);
  194. CSTR getBuildID(void)
  195. {
  196. return NULL;
  197. }
  198. /* Global Time Diff Value to correct Timestamps */
  199. static int g_iTimeDiff = 0;
  200. /**
  201. * number of seconds from 1 Jan. 1601 00:00 to 1 Jan 1970 00:00 UTC
  202. */
  203. // Defined in Header File
  204. // #define EPOCH_DIFF 11644473600LL
  205. // #define UNIX_TimeStamp_2_WINDOWS_FileTime_SHIFT 116444736000000000
  206. bool correctSysTime(int diff)
  207. {
  208. #ifdef __linux__
  209. struct timeval tData;
  210. struct timezone tTZ;
  211. tTZ.tz_minuteswest = 0;
  212. tTZ.tz_dsttime = 0;
  213. if (gettimeofday(&tData, &tTZ) == -1)
  214. {
  215. return false;
  216. }
  217. else
  218. {
  219. tData.tv_sec += diff / 1000;
  220. tData.tv_usec += (diff * 1000) % 1000000;
  221. };
  222. if (settimeofday(&tData, &tTZ) == -1)
  223. {
  224. return false;
  225. };
  226. #else
  227. unsigned __int64 tMilliseconds;
  228. SYSTEMTIME Ztime;
  229. GetSystemTime(&Ztime);
  230. SystemTimeToFileTime(&Ztime, (FILETIME *) &tMilliseconds);
  231. tMilliseconds += diff * 10000;
  232. FileTimeToSystemTime((FILETIME *) &tMilliseconds, &Ztime);
  233. if (0 == SetSystemTime(&Ztime))
  234. {
  235. return false;
  236. }
  237. #endif
  238. return true;
  239. }
  240. off_t getFileSize(const char * filename)
  241. {
  242. struct stat st;
  243. if (stat(filename, &st) == 0)
  244. {
  245. return st.st_size;
  246. }
  247. return -1;
  248. }
  249. bool correctSoftTime(int diff)
  250. {
  251. g_iTimeDiff = diff;
  252. return true;
  253. }
  254. #ifdef __linux__
  255. unsigned long long getTimeValue(void)
  256. {
  257. unsigned long long tMilliseconds;
  258. struct timeval tData;
  259. struct timezone tTZ;
  260. tMilliseconds = 0;
  261. tTZ.tz_minuteswest = 0;
  262. tTZ.tz_dsttime = 0;
  263. if (gettimeofday(&tData, &tTZ) == -1)
  264. {
  265. }
  266. else
  267. {
  268. tMilliseconds = tData.tv_sec;
  269. tMilliseconds = tMilliseconds * 1000;
  270. tMilliseconds += tData.tv_usec / 1000;
  271. };
  272. #else
  273. /*
  274. void TimetToFileTime( time_t t, LPFILETIME pft ){
  275. LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
  276. pft->dwLowDateTime = (DWORD) ll;
  277. pft->dwHighDateTime = ll >>32;
  278. }*/
  279. unsigned __int64 getTimeValue(void)
  280. {
  281. unsigned __int64 tMilliseconds;
  282. SYSTEMTIME Ztime;
  283. GetSystemTime(&Ztime);
  284. SystemTimeToFileTime(&Ztime, (FILETIME *) &tMilliseconds);
  285. tMilliseconds -= UNIX_TimeStamp_2_WINDOWS_FileTime_SHIFT;
  286. tMilliseconds = tMilliseconds / 10000;
  287. #endif
  288. tMilliseconds += g_iTimeDiff;
  289. return tMilliseconds;
  290. }
  291. static uint32_t UID_INCREMENTAL_VALUE = 0;
  292. #define UID_INCREMEMTAL (UID_INCREMENTAL_VALUE++)
  293. CSTR getTimeStamp(void)
  294. {
  295. CSTR RetVal = NULL;
  296. time_t rawtime;
  297. uint32_t msec;
  298. struct tm * ptm = NULL;
  299. time(&rawtime);
  300. ptm = gmtime(&rawtime);
  301. msec = getTimeValue() % 1000;
  302. // 2019-03-24T12:32:59.670Z
  303. if (ptm != NULL)
  304. {
  305. RetVal = (CSTR) malloc(128);
  306. if (RetVal != NULL)
  307. {
  308. sprintf(RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, msec);
  309. };
  310. };
  311. return RetVal;
  312. }
  313. CSTR getTimeStampI(void)
  314. {
  315. CSTR RetVal = NULL;
  316. time_t rawtime;
  317. uint32_t msec;
  318. struct tm * ptm = NULL;
  319. time(&rawtime);
  320. ptm = gmtime(&rawtime);
  321. msec = getTimeValue() % 1000;
  322. // 2019-03-24T12:32:59.670Z
  323. if (ptm != NULL)
  324. {
  325. RetVal = (CSTR) malloc(128);
  326. if (RetVal != NULL)
  327. {
  328. sprintf(RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ %d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, msec, UID_INCREMEMTAL);
  329. };
  330. };
  331. return RetVal;
  332. }
  333. CSTR getUniqID_MD5(void)
  334. {
  335. CSTR tVal = NULL;
  336. CSTR tMD5 = NULL;
  337. char buf[33];
  338. tVal = getTimeStampI();
  339. buf[0] = (char) 0;
  340. if (tVal)
  341. {
  342. tMD5 = MD5String(tVal);
  343. if (tMD5)
  344. {
  345. sprintf(buf, "%s", tMD5);
  346. free(tMD5);
  347. };
  348. free(tVal);
  349. };
  350. #ifdef __linux__
  351. return strdup(buf);
  352. #else
  353. return _strdup(buf);
  354. #endif
  355. }
  356. CSTR getUniqID_SHA256(void)
  357. {
  358. return NULL;
  359. }
  360. int rand(int a, int b)
  361. {
  362. if (b > a)
  363. {
  364. return a + (rand() * (b - a)) / RAND_MAX;
  365. };
  366. return b + (rand() * (a - b)) / RAND_MAX;
  367. }
  368. void getUniqID_UUID(CSTR buf, uint32_t SEED)
  369. {
  370. CSTR tVal = NULL;
  371. CSTR tMD5 = NULL;
  372. tVal = getTimeStamp();
  373. buf[0] = (char) 0;
  374. if (tVal)
  375. {
  376. char tt[256];
  377. sprintf(tt, "%s %d %d", tVal, SEED, UID_INCREMEMTAL);
  378. tMD5 = MD5String(tt);
  379. if (tMD5)
  380. {
  381. memcpy(buf, tMD5, 8);
  382. buf[8] = '-';
  383. memcpy(buf + 9, tMD5 + 8, 4);
  384. buf[13] = '-';
  385. memcpy(buf + 14, tMD5 + 12, 4);
  386. buf[18] = '-';
  387. memcpy(buf + 19, tMD5 + 16, 4);
  388. buf[23] = '-';
  389. memcpy(buf + 24, tMD5 + 20, 12);
  390. buf[36] = (char) 0;
  391. free(tMD5);
  392. };
  393. free(tVal);
  394. };
  395. }
  396. CSTR getUniqID_UUID(uint32_t SEED)
  397. {
  398. char buf[37];
  399. getUniqID_UUID(buf, SEED);
  400. #ifdef __linux__
  401. return strdup(buf);
  402. #else
  403. return _strdup(buf);
  404. #endif
  405. }
  406. CSTR trim(CSTR val)
  407. {
  408. int i = 0;
  409. int j = strlen(val);
  410. if (j)
  411. {
  412. while ((i < j) && (((unsigned char) val[i]) < 0x21))
  413. {
  414. i++;
  415. }
  416. while ((j > i) && (((unsigned char) val[j]) < 0x21))
  417. {
  418. j--;
  419. }
  420. if ((i > 0) && ((j - i + 1) > 0))
  421. {
  422. memmove(val, val + i, j - i + 1); // regions overlap: memcpy is undefined here
  423. }
  424. val[j - i + 1] = (char) 0;
  425. };
  426. return val;
  427. }
  428. // orig - input String to Search In
  429. // rep - token to search
  430. // with - replacement for token
  431. // in case with is NULL - cutting off the token
  432. // You must free the result if result is non-NULL.
  433. CSTR strReplace(CSTR orig, CSTR rep, CSTR with)
  434. {
  435. char * result; // the return string
  436. char * ins; // the next insert point
  437. char * tmp; // varies
  438. int len_rep; // length of rep (the string to remove)
  439. int len_with; // length of with (the string to replace rep with)
  440. int len_front; // distance between rep and end of last rep
  441. int count; // number of replacements
  442. // sanity checks and initialization
  443. if (! orig || ! rep)
  444. {
  445. return NULL;
  446. }
  447. len_rep = strlen(rep);
  448. if (len_rep == 0)
  449. {
  450. return NULL; // empty rep causes infinite loop during count
  451. }
  452. if (! with)
  453. {
  454. with = (CSTR) ""; // In case With not suplied - just cut off Token
  455. }
  456. len_with = strlen(with);
  457. // count the number of replacements needed
  458. ins = orig;
  459. for (count = 0; (tmp = strstr(ins, rep)); ++count)
  460. {
  461. ins = tmp + len_rep;
  462. }
  463. tmp = result = (CSTR) malloc(strlen(orig) + (len_with - len_rep) * count + 1);
  464. if (! result)
  465. {
  466. return NULL;
  467. }
  468. // first time through the loop, all the variable are set correctly
  469. // from here on,
  470. // tmp points to the end of the result string
  471. // ins points to the next occurrence of rep in orig
  472. // orig points to the remainder of orig after "end of rep"
  473. while (count--)
  474. {
  475. ins = strstr(orig, rep);
  476. len_front = ins - orig;
  477. tmp = strncpy(tmp, orig, len_front) + len_front;
  478. tmp = strcpy(tmp, with) + len_with;
  479. orig += len_front + len_rep; // move to next "end of rep"
  480. }
  481. strcpy(tmp, orig);
  482. return result;
  483. }
  484. uint8_t checksum8(uint8_t * Buffer, size_t BufferSize)
  485. {
  486. uint16_t TempVal;
  487. TempVal = 0;
  488. for (size_t index = 0; index < BufferSize; index++)
  489. {
  490. TempVal += Buffer[index];
  491. };
  492. return (uint8_t) (TempVal & 0x00FF);
  493. }
  494. uint16_t checksum16(uint8_t * Buffer, size_t BufferSize)
  495. {
  496. uint32_t TempVal;
  497. TempVal = 0;
  498. for (size_t index = 0; index < BufferSize; index++)
  499. {
  500. TempVal += Buffer[index];
  501. };
  502. return (uint16_t) (TempVal & 0x0000FFFF);
  503. }
  504. uint8_t checksumLGS(uint8_t * Buffer, size_t BufferSize)
  505. {
  506. uint16_t TempVal;
  507. TempVal = 0;
  508. for (size_t index = 0; index < BufferSize; index++)
  509. {
  510. TempVal += Buffer[index];
  511. };
  512. return (uint8_t) (TempVal & 0x00FF);
  513. }
  514. // Calculating the Check Sum for Ping package
  515. uint16_t checksumPing(void * b, size_t len)
  516. {
  517. uint16_t * buf = (uint16_t *) b;
  518. uint32_t sum = 0;
  519. uint16_t result;
  520. for (sum = 0; len > 1; len -= 2)
  521. {
  522. sum += *buf++;
  523. }
  524. if (len == 1)
  525. {
  526. sum += *(unsigned char *) buf;
  527. }
  528. sum = (sum >> 16) + (sum & 0xFFFF);
  529. sum += (sum >> 16);
  530. result = ~sum;
  531. return result;
  532. }
  533. // Calculating the Check Sum
  534. /*unsigned short checksum(void *b, int len){
  535. unsigned short *buf = (unsigned short *) b;
  536. unsigned int sum=0;
  537. unsigned short result;
  538. for ( sum = 0; len > 1; len -= 2 )
  539. sum += *buf++;
  540. if ( len == 1 )
  541. sum += *(unsigned char*)buf;
  542. sum = (sum >> 16) + (sum & 0xFFFF);
  543. sum += (sum >> 16);
  544. result = ~sum;
  545. return result;
  546. }*/
  547. CArray * explode(char Delim, CSTR S_Str)
  548. {
  549. bool ws = false;
  550. CArray * RetVal = NULL;
  551. CSTR b_ptr = S_Str;
  552. U16 s_ptr = 0;
  553. if (S_Str)
  554. {
  555. RetVal = new CArray;
  556. if (RetVal)
  557. {
  558. while ((U8) S_Str[s_ptr])
  559. {
  560. if (((U8) Delim) == ((U8) S_Str[s_ptr]))
  561. {
  562. if (! ws)
  563. {
  564. ws = true;
  565. S_Str[s_ptr] = (char) 0;
  566. RetVal->push_back(b_ptr);
  567. s_ptr++;
  568. b_ptr = &S_Str[s_ptr];
  569. }
  570. else
  571. {
  572. s_ptr++;
  573. }
  574. }
  575. else
  576. {
  577. ws = false;
  578. s_ptr++;
  579. };
  580. };
  581. RetVal->push_back(b_ptr);
  582. };
  583. };
  584. return RetVal;
  585. }
  586. CSTR implode(CArray * Data, CSTR S_Str, U8 Start, U8 End)
  587. {
  588. CSTR RetVal;
  589. U8 RStart = Start;
  590. U8 REnd = End;
  591. if (Start > Data->size())
  592. {
  593. return NULL;
  594. }
  595. if (End < Start)
  596. {
  597. return NULL;
  598. }
  599. if (End > Data->size())
  600. {
  601. REnd = (U8) (Data->size() - 1);
  602. }
  603. if (strlen((*Data).at(RStart)))
  604. {
  605. RetVal = (CSTR) malloc(strlen((*Data).at(RStart)) + 1);
  606. sprintf(RetVal, "%s", (*Data).at(RStart));
  607. }
  608. else
  609. {
  610. RetVal = (CSTR) malloc(1);
  611. *RetVal = (char) 0;
  612. };
  613. if (RetVal != NULL)
  614. {
  615. for (int i = RStart + 1; i < REnd; i++)
  616. {
  617. RetVal = (CSTR) realloc(RetVal, strlen(RetVal) + strlen((*Data).at(i)) + 1 + strlen(S_Str));
  618. CSTR tV = RetVal;
  619. sprintf(RetVal, "%s%s%s", tV, S_Str, (*Data).at(i));
  620. };
  621. };
  622. return RetVal;
  623. }
  624. int getIP4(if_info ** arrParam, int max_ifs)
  625. {
  626. int index = 0;
  627. #ifdef __linux__
  628. struct ifaddrs *addrs, *tmp;
  629. getifaddrs(&addrs);
  630. tmp = addrs;
  631. // arrParam= malloc( 10 * sezeof(if_info) );
  632. while (tmp)
  633. {
  634. if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET)
  635. {
  636. if (strncmp(tmp->ifa_name, "lo", 2) != 0)
  637. {
  638. (*arrParam)[index].if_name = (CSTR) malloc(strlen(tmp->ifa_name) + 1);
  639. snprintf((*arrParam)[index].if_name, strlen(tmp->ifa_name) + 1, "%s", tmp->ifa_name);
  640. (*arrParam)[index].if_addr = (CSTR) malloc(16);
  641. struct sockaddr_in * pAddr = (struct sockaddr_in *) tmp->ifa_addr;
  642. snprintf((*arrParam)[index].if_addr, 16, "%s", inet_ntoa(pAddr->sin_addr));
  643. index++;
  644. if (index == max_ifs)
  645. {
  646. break;
  647. }
  648. }
  649. };
  650. tmp = tmp->ifa_next;
  651. };
  652. freeifaddrs(addrs);
  653. #endif
  654. return index;
  655. }
  656. #ifdef __linux__
  657. long long getFreeSpace(CSTR DirName)
  658. {
  659. struct statvfs fiData;
  660. if ((statvfs(DirName, &fiData)) < 0)
  661. {
  662. return -1;
  663. };
  664. return fiData.f_bsize * fiData.f_bfree;
  665. }
  666. long long getTotalSpace(CSTR DirName)
  667. {
  668. struct statvfs fiData;
  669. if ((statvfs(DirName, &fiData)) < 0)
  670. {
  671. return -1;
  672. };
  673. return fiData.f_bsize * fiData.f_blocks;
  674. }
  675. #else
  676. __int64 getFreeSpace(CSTR DirName)
  677. {
  678. return -1;
  679. }
  680. __int64 getTotalSpace(CSTR DirName)
  681. {
  682. return -1;
  683. }
  684. #endif
  685. CSTR getTStr(CSTR Fmt)
  686. {
  687. // CSTR RetVal = NULL;
  688. char DateStr[200];
  689. time_t t;
  690. struct tm * tmp;
  691. t = time(NULL);
  692. tmp = gmtime(&t);
  693. if (tmp == NULL)
  694. {
  695. fprintf(stderr, "localtime!");
  696. return NULL;
  697. };
  698. if (Fmt == NULL)
  699. {
  700. if (strftime(DateStr, 200, "%F %T GMT", tmp) == 0)
  701. {
  702. fprintf(stderr, "strftime returned 0");
  703. return NULL;
  704. };
  705. }
  706. else
  707. {
  708. if (strftime(DateStr, 200, Fmt, tmp) == 0)
  709. {
  710. fprintf(stderr, "strftime returned 0");
  711. return NULL;
  712. };
  713. }
  714. // RetVal =(CSTR) malloc( strlen(DateStr) +1 );
  715. // if( RetVal != NULL ) strcpy( RetVal, DateStr );
  716. #ifdef __linux__
  717. return strdup(DateStr);
  718. #else
  719. return _strdup(DateStr);
  720. #endif
  721. }
  722. #ifdef __linux__
  723. int xioctl(int fh, unsigned long request, void * arg)
  724. {
  725. int r;
  726. do
  727. {
  728. r = ioctl(fh, request, arg);
  729. }
  730. while (-1 == r && EINTR == errno);
  731. return r;
  732. }
  733. uint64_t getMilliseconds(void)
  734. {
  735. uint64_t tMilliseconds = (uint64_t) 0;
  736. struct timeval tData;
  737. struct timezone tTZ;
  738. tTZ.tz_minuteswest = 0;
  739. tTZ.tz_dsttime = 0;
  740. if( gettimeofday( &tData, &tTZ ) == -1 ){
  741. tMilliseconds = (uint64_t) 0;
  742. #ifdef DEBUG
  743. URGENT_LOG("gettimeofday error!");
  744. #endif
  745. } else {
  746. tMilliseconds = (uint64_t) ( tData.tv_sec - ( tTZ.tz_minuteswest * 60 ) ); //Correcting TZ shift
  747. tMilliseconds = (tMilliseconds * 1000);
  748. tMilliseconds += (uint64_t) (tData.tv_usec / 1000);
  749. };
  750. return tMilliseconds;
  751. }
  752. #else // !__linux__
  753. #include <ctime>
  754. unsigned __int64 getMilliseconds(void)
  755. {
  756. unsigned __int64 tMilliseconds;
  757. SYSTEMTIME time;
  758. GetSystemTime(&time);
  759. tMilliseconds = (uint32_t) std::time(NULL);
  760. tMilliseconds *= 1000;
  761. tMilliseconds += time.wMilliseconds;
  762. return tMilliseconds;
  763. }
  764. #endif
  765. #ifdef __linux__
  766. #ifndef USE_SYSTEM_CALL_TO_PING
  767. #include <netinet/ip_icmp.h>
  768. // Define the Packet Constants
  769. // ping packet size
  770. #define PING_PKT_S 64
  771. // Automatic port number
  772. #define PORT_NO 0
  773. // Automatic port number
  774. #define PING_SLEEP_RATE 1000000
  775. // Gives the timeout delay for receiving packets
  776. // in seconds
  777. #define RECV_TIMEOUT 1
  778. // ping packet structure
  779. struct ping_pkt
  780. {
  781. struct icmphdr hdr;
  782. char msg[PING_PKT_S - sizeof(struct icmphdr)];
  783. };
  784. #endif //! USE_SYSTEM_CALL_TO_PING
  785. bool pingIP4(CSTR ip4)
  786. {
  787. #ifdef USE_SYSTEM_CALL_TO_PING
  788. // Ping google.com once, redirect output to /dev/null, and check the return value
  789. char tB[256];
  790. sprintf(tB, "ping -c 1 -W 0.5 -4 %s > /dev/null 2>&1", ip4);
  791. if (system(tB) == 0)
  792. {
  793. return true;
  794. }
  795. return false;
  796. #else // !USE_SYSTEM_CALL_TO_PING
  797. bool RetVal = false;
  798. if (ip4 == NULL)
  799. {
  800. return false;
  801. }
  802. if (strlen(ip4) < 7)
  803. {
  804. return false;
  805. }
  806. #ifdef DEBUG_EXTRA
  807. URGENT_LOG("Pinging Device!");
  808. #endif
  809. int sockfd;
  810. int ttl_val = 64, msg_count = 0, i, flag = 1, msg_received_count = 0;
  811. struct ping_pkt pckt;
  812. struct sockaddr_in ping_addr;
  813. struct sockaddr_in r_addr;
  814. struct timeval tv_out;
  815. tv_out.tv_sec = 0;
  816. tv_out.tv_usec = 300000; // 1/3 of second
  817. ping_addr.sin_family = AF_INET;
  818. ping_addr.sin_addr.s_addr = inet_addr(ip4);
  819. // ping_addr.sin_port = htons( m_nPort );
  820. #ifdef DEBUG_EXTRA
  821. URGENT_LOG(ip4);
  822. #endif
  823. sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  824. if (sockfd < 0)
  825. {
  826. URGENT_LOG("Socket file descriptor not received!");
  827. return false;
  828. };
  829. // set socket options at ip to TTL and value to 64,
  830. // change to what you want by setting ttl_val
  831. if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0)
  832. {
  833. URGENT_LOG("Setting socket options to TTL failed!");
  834. shutdown(sockfd, SHUT_RDWR);
  835. return false;
  836. };
  837. // setting timeout of recv setting
  838. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv_out, sizeof tv_out);
  839. // flag is whether packet was sent or not
  840. flag = 1;
  841. // filling packet
  842. bzero(&pckt, sizeof(pckt));
  843. pckt.hdr.type = ICMP_ECHO;
  844. pckt.hdr.un.echo.id = getpid();
  845. for (i = 0; i < sizeof(pckt.msg) - 1; i++)
  846. {
  847. pckt.msg[i] = i + '0';
  848. }
  849. pckt.msg[i] = 0;
  850. pckt.hdr.un.echo.sequence = msg_count++;
  851. pckt.hdr.checksum = checksumPing(&pckt, sizeof(pckt));
  852. // SLEEP( 300 );
  853. // send packet
  854. if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &ping_addr, sizeof(ping_addr)) <= 0)
  855. {
  856. URGENT_LOG("Packet Sending Failed!");
  857. shutdown(sockfd, SHUT_RDWR);
  858. return false;
  859. };
  860. // receive packet
  861. socklen_t addr_len = sizeof(r_addr);
  862. if (recvfrom(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &r_addr, &addr_len) <= 0)
  863. {
  864. #ifdef DEBUG_EXTRA
  865. URGENT_LOG("Packet receive failed!");
  866. #endif
  867. }
  868. else
  869. {
  870. #ifdef DEBUG_EXTRA
  871. URGENT_LOG("Device pinged Sucessfully");
  872. #endif
  873. RetVal = true;
  874. };
  875. shutdown(sockfd, SHUT_RDWR);
  876. return RetVal;
  877. #endif //! USE_SYSTEM_CALL_TO_PING
  878. }
  879. bool enumerateDevices(enumeratorInfo * mlist, const char * dTemplate)
  880. {
  881. DIR * d;
  882. struct dirent * dir;
  883. DeviceInfo * tDevInfo;
  884. if (mlist == NULL)
  885. {
  886. return false;
  887. }
  888. if (dTemplate == NULL)
  889. {
  890. return false;
  891. }
  892. for (size_t i = 0; i < mlist->size(); i++)
  893. {
  894. delete(mlist->at(i));
  895. };
  896. mlist->clear();
  897. d = opendir("/dev");
  898. if (d)
  899. {
  900. while ((dir = readdir(d)) != NULL)
  901. {
  902. if (dir->d_type == DT_CHR || dir->d_type == DT_BLK)
  903. {
  904. if (strncmp(dir->d_name, dTemplate, 5) == 0)
  905. {
  906. tDevInfo = (DeviceInfo *) malloc(sizeof(DeviceInfo));
  907. sprintf(tDevInfo->DevicePath, "/dev/%s", dir->d_name);
  908. tDevInfo->FriendlyName[0] = (char) 0;
  909. if (strncmp(dTemplate, "video", 5) == 0)
  910. {
  911. FILE * fd;
  912. char CMD[1100];
  913. sprintf(CMD, "v4l2-ctl -d %s -D", tDevInfo->DevicePath);
  914. fd = popen(CMD, "r");
  915. if (fd != NULL)
  916. {
  917. char * line = NULL;
  918. size_t len = 0;
  919. ssize_t rd;
  920. while ((rd = getline(&line, &len, fd)) != -1)
  921. {
  922. char *tS1, *tS2;
  923. // Future use strcasestr() or make both stings same case
  924. if ((tS1 = strstr(line, "Bus info")) != NULL)
  925. {
  926. tS2 = trim(strstr(tS1, ":") + 2);
  927. sprintf(tDevInfo->FriendlyName, "%s", tS2);
  928. };
  929. };
  930. fclose(fd);
  931. if (line)
  932. {
  933. free(line);
  934. }
  935. };
  936. };
  937. mlist->push_back(tDevInfo);
  938. // printf("%s\n", dir->d_name );
  939. };
  940. // if( strncmp( dir->d_name, "ttyS", 4 ) == 0 ){
  941. // tBuffer = ( char * ) malloc( strlen(dir->d_name)+1 );
  942. // strncpy( tBuffer, dir->d_name, strlen(dir->d_name)+1 );
  943. // mlist->pushBack( tBuffer );
  944. // //printf("%s\n", dir->d_name );
  945. // };
  946. };
  947. };
  948. closedir(d);
  949. }
  950. else
  951. {
  952. return false;
  953. };
  954. return true;
  955. }
  956. #else
  957. #ifndef IID_PPV_ARGS
  958. extern "C++"
  959. {
  960. template <typename T> void ** IID_PPV_ARGS_Helper(T ** pp)
  961. {
  962. // make sure everyone derives from IUnknown
  963. static_cast<IUnknown *>(*pp);
  964. return reinterpret_cast<void **>(pp);
  965. }
  966. }
  967. #define IID_PPV_ARGS(ppType) __uuidof(**(ppType)), IID_PPV_ARGS_Helper(ppType)
  968. #endif
  969. #pragma comment(lib, "Strmiids.lib")
  970. bool enumerateDevices(enumeratorInfo * mlist, REFGUID category)
  971. {
  972. HRESULT hr;
  973. bool initOk = true;
  974. hr = CoInitializeEx(NULL, COINIT_SPEED_OVER_MEMORY | COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
  975. if (hr == E_INVALIDARG)
  976. {
  977. printf("Couldn't Init! hr=0x%x", hr);
  978. return false;
  979. }
  980. else if (hr == E_OUTOFMEMORY)
  981. {
  982. printf("Couldn't Init! hr=0x%x", hr);
  983. return false;
  984. }
  985. else if (hr == E_UNEXPECTED)
  986. {
  987. printf("Couldn't Init! hr=0x%x", hr);
  988. return false;
  989. }
  990. else if (hr == RPC_E_CHANGED_MODE)
  991. {
  992. initOk = false;
  993. };
  994. if (hr == S_OK || hr == RPC_E_CHANGED_MODE)
  995. {
  996. // Create the system device enumerator
  997. ICreateDevEnum * pDevEnum;
  998. hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum));
  999. if (hr != S_OK)
  1000. {
  1001. printf("Couldn't create system enumerator! hr=0x%x", hr);
  1002. CoUninitialize();
  1003. return false;
  1004. };
  1005. if (pDevEnum != NULL)
  1006. {
  1007. IEnumMoniker * pClsEnum = NULL;
  1008. hr = pDevEnum->CreateClassEnumerator(category, &pClsEnum, 0);
  1009. if (hr == S_FALSE)
  1010. {
  1011. // The category is empty. Treat as an error.
  1012. pDevEnum->Release();
  1013. CoUninitialize();
  1014. return false;
  1015. };
  1016. if (pClsEnum != NULL)
  1017. {
  1018. IMoniker * pMoniker = NULL;
  1019. while (pClsEnum->Next(1, &pMoniker, NULL) == S_OK)
  1020. {
  1021. IPropertyBag * pPropBag = NULL;
  1022. hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
  1023. if (FAILED(hr))
  1024. {
  1025. pMoniker->Release();
  1026. continue;
  1027. };
  1028. VARIANT var;
  1029. VariantInit(&var);
  1030. DeviceInfo * tRec;
  1031. tRec = (DeviceInfo *) malloc(sizeof(DeviceInfo));
  1032. // Get description or friendly name.
  1033. hr = pPropBag->Read(L"Description", &var, 0);
  1034. if (FAILED(hr))
  1035. {
  1036. hr = pPropBag->Read(L"FriendlyName", &var, 0);
  1037. };
  1038. if (SUCCEEDED(hr))
  1039. {
  1040. if (tRec != NULL)
  1041. {
  1042. sprintf(tRec->FriendlyName, "%S", var.bstrVal);
  1043. mlist->push_back(tRec);
  1044. };
  1045. VariantClear(&var);
  1046. };
  1047. hr = pPropBag->Write(L"FriendlyName", &var);
  1048. // WaveInID applies only to audio capture devices.
  1049. hr = pPropBag->Read(L"WaveInID", &var, 0);
  1050. if (SUCCEEDED(hr))
  1051. {
  1052. // printf("WaveIn ID: %d\n", var.lVal);
  1053. VariantClear(&var);
  1054. };
  1055. hr = pPropBag->Read(L"DevicePath", &var, 0);
  1056. if (SUCCEEDED(hr))
  1057. {
  1058. // The device path is not intended for display.
  1059. if (tRec != NULL)
  1060. {
  1061. sprintf(tRec->DevicePath, "%S", var.bstrVal);
  1062. };
  1063. VariantClear(&var);
  1064. };
  1065. pPropBag->Release();
  1066. pMoniker->Release();
  1067. };
  1068. pClsEnum->Release();
  1069. };
  1070. pDevEnum->Release();
  1071. };
  1072. if (initOk)
  1073. {
  1074. CoUninitialize();
  1075. }
  1076. };
  1077. return true;
  1078. }
  1079. #endif
  1080. size_t escape_string(char * to, size_t to_length, const char * from, size_t length)
  1081. {
  1082. const char * to_start = to;
  1083. const char * end, *to_end = to_start + (to_length ? to_length - 1 : 2 * length);
  1084. bool overflow = false;
  1085. for (end = from + length; from < end; from++)
  1086. {
  1087. char escape = 0;
  1088. int tmp_length;
  1089. /*
  1090. If the next character appears to begin a multi-byte character, we
  1091. escape that first byte of that apparent multi-byte character. (The
  1092. character just looks like a multi-byte character -- if it were actually
  1093. a multi-byte character, it would have been passed through in the test
  1094. above.)
  1095. Without this check, we can create a problem by converting an invalid
  1096. multi-byte character into a valid one. For example, 0xbf27 is not
  1097. a valid GBK character, but 0xbf5c is. (0x27 = ', 0x5c = \)
  1098. */
  1099. tmp_length = 0;
  1100. if (tmp_length > 1)
  1101. {
  1102. escape = *from;
  1103. }
  1104. else
  1105. {
  1106. switch (*from)
  1107. {
  1108. case 0 : /* Must be escaped for 'mysql' */ escape = '0'; break;
  1109. case '\n' : /* Must be escaped for logs */ escape = 'n'; break;
  1110. case '\r' : escape = 'r'; break;
  1111. case '\\' : escape = '\\'; break;
  1112. case '\'' : escape = '\''; break;
  1113. case '"' : /* Better safe than sorry */ escape = '"'; break;
  1114. case '\032': /* This gives problems on Win32 */ escape = 'Z'; break;
  1115. };
  1116. };
  1117. if (escape)
  1118. {
  1119. if (to + 2 > to_end)
  1120. {
  1121. overflow = true;
  1122. break;
  1123. };
  1124. *to++ = '\\';
  1125. *to++ = escape;
  1126. }
  1127. else
  1128. {
  1129. if (to + 1 > to_end)
  1130. {
  1131. overflow = true;
  1132. break;
  1133. };
  1134. *to++ = *from;
  1135. };
  1136. };
  1137. *to = 0;
  1138. return overflow ? (size_t) -1 : (size_t) (to - to_start);
  1139. }
  1140. /* Read characters from 'fd' until a newline is encountered. If a newline
  1141. character is not encountered in the first (n - 1) bytes, then the excess
  1142. characters are discarded. The returned string placed in 'buf' is
  1143. null-terminated and includes the newline character if it was read in the
  1144. first (n - 1) bytes. The function return value is the number of bytes
  1145. placed in buffer (which includes the newline character if encountered,
  1146. but excludes the terminating null byte). */
  1147. ssize_t readLine(int fd, char * buffer, size_t n)
  1148. {
  1149. ssize_t numRead; /* # of bytes fetched by last read() */
  1150. size_t totRead; /* Total bytes read so far */
  1151. char * buf;
  1152. char ch;
  1153. if (n <= 0 || buffer == NULL)
  1154. {
  1155. errno = EINVAL;
  1156. return -1;
  1157. }
  1158. buf = buffer; /* No pointer arithmetic on "void *" */
  1159. totRead = 0;
  1160. for (;;)
  1161. {
  1162. numRead = read(fd, &ch, 1);
  1163. if (numRead == -1)
  1164. {
  1165. if (errno == EINTR) /* Interrupted --> restart read() */
  1166. {
  1167. continue;
  1168. }
  1169. else
  1170. {
  1171. return -1; /* Some other error */
  1172. }
  1173. }
  1174. else if (numRead == 0)
  1175. { /* EOF */
  1176. if (totRead == 0) /* No bytes read; return 0 */
  1177. {
  1178. return 0;
  1179. }
  1180. else /* Some bytes read; add '\0' */
  1181. {
  1182. break;
  1183. }
  1184. }
  1185. else
  1186. { /* 'numRead' must be 1 if we get here */
  1187. if (totRead < n - 1)
  1188. { /* Discard > (n - 1) bytes */
  1189. totRead++;
  1190. *buf++ = ch;
  1191. }
  1192. if (ch == '\n')
  1193. {
  1194. break;
  1195. }
  1196. }
  1197. }
  1198. *buf = '\0';
  1199. return totRead;
  1200. }
  1201. ssize_t readLine(FILE * fd, char * buffer, size_t n)
  1202. {
  1203. ssize_t numRead; /* # of bytes fetched by last read() */
  1204. size_t totRead; /* Total bytes read so far */
  1205. char * buf;
  1206. char ch;
  1207. if (n <= 0 || buffer == NULL)
  1208. {
  1209. errno = EINVAL;
  1210. return -1;
  1211. }
  1212. buf = buffer; /* No pointer arithmetic on "void *" */
  1213. totRead = 0;
  1214. for (;;)
  1215. {
  1216. numRead = fread(&ch, 1, 1, fd);
  1217. if (numRead == -1)
  1218. {
  1219. if (errno == EINTR) /* Interrupted --> restart read() */
  1220. {
  1221. continue;
  1222. }
  1223. else
  1224. {
  1225. return -1; /* Some other error */
  1226. }
  1227. }
  1228. else if (numRead == 0)
  1229. { /* EOF */
  1230. if (totRead == 0) /* No bytes read; return 0 */
  1231. {
  1232. return 0;
  1233. }
  1234. else /* Some bytes read; add '\0' */
  1235. {
  1236. break;
  1237. }
  1238. }
  1239. else
  1240. { /* 'numRead' must be 1 if we get here */
  1241. if (totRead < n - 1)
  1242. { /* Discard > (n - 1) bytes */
  1243. totRead++;
  1244. *buf++ = ch;
  1245. }
  1246. if (ch == '\n')
  1247. {
  1248. break;
  1249. }
  1250. }
  1251. }
  1252. *buf = '\0';
  1253. return totRead;
  1254. }
  1255. localIpAddresses g_vLocalIpAdressess;
  1256. bool g_bAdressesAreDiscovered = false;
  1257. #ifdef __linux__
  1258. bool isProcessUniq(CSTR pName)
  1259. {
  1260. char tB[256];
  1261. FILE * fd;
  1262. sprintf(tB, "pidof %s", pName);
  1263. fd = popen(tB, "r");
  1264. if (fd)
  1265. {
  1266. int rs = readLine(fd, tB, 256);
  1267. if (rs > 2)
  1268. {
  1269. fclose(fd);
  1270. return false;
  1271. };
  1272. fclose(fd);
  1273. };
  1274. return true;
  1275. }
  1276. #include <linux/if.h>
  1277. localIpAddresses * getLocalIP()
  1278. {
  1279. // Check for Filter LO and TUN Devices!
  1280. if (! g_bAdressesAreDiscovered)
  1281. {
  1282. struct ifaddrs *ifaddr, *ifa;
  1283. localIp4Info * tIpAddress = NULL;
  1284. if (getifaddrs(&ifaddr) != -1)
  1285. {
  1286. /* Walk through linked list, maintaining head pointer so we can free list later */
  1287. for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
  1288. {
  1289. // Filter Loopback if
  1290. if (strstr(ifa->ifa_name, "lo") != NULL)
  1291. {
  1292. continue;
  1293. }
  1294. // Filter vpn TUN if
  1295. if (strstr(ifa->ifa_name, "tun") != NULL)
  1296. {
  1297. continue;
  1298. }
  1299. //char protocol[IFNAMSIZ] = {0};
  1300. if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
  1301. {
  1302. continue;
  1303. }
  1304. tIpAddress = (localIp4Info *) malloc(sizeof(localIp4Info));
  1305. if (tIpAddress != NULL)
  1306. {
  1307. sprintf(tIpAddress->address, "%d.%d.%d.%d", (uint8_t) ifa->ifa_addr->sa_data[2], (uint8_t) ifa->ifa_addr->sa_data[3], (uint8_t) ifa->ifa_addr->sa_data[4], (uint8_t) ifa->ifa_addr->sa_data[5]);
  1308. sprintf(tIpAddress->netmask, "%d.%d.%d.%d", (uint8_t) ifa->ifa_netmask->sa_data[2], (uint8_t) ifa->ifa_netmask->sa_data[3], (uint8_t) ifa->ifa_netmask->sa_data[4], (uint8_t) ifa->ifa_netmask->sa_data[5]);
  1309. sprintf(tIpAddress->broadcast, "%d.%d.%d.%d", (uint8_t) ifa->ifa_ifu.ifu_broadaddr->sa_data[2], (uint8_t) ifa->ifa_ifu.ifu_broadaddr->sa_data[3], (uint8_t) ifa->ifa_ifu.ifu_broadaddr->sa_data[4],
  1310. (uint8_t) ifa->ifa_ifu.ifu_broadaddr->sa_data[5]);
  1311. g_vLocalIpAdressess.push_back(tIpAddress);
  1312. };
  1313. };
  1314. freeifaddrs(ifaddr);
  1315. };
  1316. g_bAdressesAreDiscovered = true;
  1317. };
  1318. return &g_vLocalIpAdressess;
  1319. }
  1320. #else // !linux
  1321. // https://stackoverflow.com/questions/5213629/how-to-enumerate-all-available-network-interfaces
  1322. #include <iphlpapi.h>
  1323. #pragma comment(lib, "IPHLPAPI.lib")
  1324. localIpAddresses * getLocalIP()
  1325. {
  1326. char psBuffer[128];
  1327. FILE * fd;
  1328. BYTE mB;
  1329. localIp4Info * tIpAddress;
  1330. if (! g_bAdressesAreDiscovered)
  1331. {
  1332. ULONG outBufLen = 0;
  1333. DWORD dwRetVal = 0;
  1334. IP_ADAPTER_INFO * pAdapterInfos = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO));
  1335. // retry up to 5 times, to get the adapter infos needed
  1336. for (int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i)
  1337. {
  1338. dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen);
  1339. if (dwRetVal == NO_ERROR)
  1340. {
  1341. break;
  1342. }
  1343. else
  1344. {
  1345. if (dwRetVal == ERROR_BUFFER_OVERFLOW)
  1346. {
  1347. free(pAdapterInfos);
  1348. pAdapterInfos = (IP_ADAPTER_INFO *) malloc(outBufLen);
  1349. }
  1350. else
  1351. {
  1352. // pAdapterInfos = 0;
  1353. break;
  1354. };
  1355. };
  1356. };
  1357. if (dwRetVal == NO_ERROR)
  1358. {
  1359. IP_ADAPTER_INFO * pAdapterInfo = pAdapterInfos;
  1360. while (pAdapterInfo)
  1361. {
  1362. IP_ADDR_STRING * pIpAddress = &(pAdapterInfo->IpAddressList);
  1363. while (pIpAddress != 0)
  1364. {
  1365. uint8_t A, B, C, D;
  1366. uint8_t M, O, S, K, G, U, T, E;
  1367. uint32_t Z1, Z2, Z3, Z4;
  1368. int RetVal;
  1369. RetVal = sscanf(pIpAddress->IpAddress.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  1370. A = Z1 & 0xFF;
  1371. B = Z2 & 0xFF;
  1372. C = Z3 & 0xFF;
  1373. D = Z4 & 0xFF;
  1374. RetVal = sscanf(pIpAddress->IpMask.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  1375. M = Z1 & 0xFF;
  1376. O = Z2 & 0xFF;
  1377. S = Z3 & 0xFF;
  1378. K = Z4 & 0xFF;
  1379. //
  1380. // <<<<
  1381. // here pAdapterInfo->Address should contain the MAC address
  1382. // >>>>
  1383. //
  1384. if (A > 0)
  1385. {
  1386. tIpAddress = (localIp4Info *) malloc(sizeof(localIp4Info));
  1387. if (tIpAddress != NULL)
  1388. {
  1389. sprintf(tIpAddress->address, "%d.%d.%d.%d", A, B, C, D);
  1390. sprintf(tIpAddress->netmask, "%d.%d.%d.%d", M, O, S, K);
  1391. G = (A & M) | (~M);
  1392. U = (B & O) | (~O);
  1393. T = (C & S) | (~S);
  1394. E = (D & K) | (~K);
  1395. sprintf(tIpAddress->broadcast, "%d.%d.%d.%d", G, U, T, E);
  1396. g_vLocalIpAdressess.push_back(tIpAddress);
  1397. };
  1398. };
  1399. pIpAddress = pIpAddress->Next;
  1400. };
  1401. pAdapterInfo = pAdapterInfo->Next;
  1402. };
  1403. };
  1404. free(pAdapterInfos);
  1405. };
  1406. return &g_vLocalIpAdressess;
  1407. }
  1408. #endif
  1409. #ifdef DEBUG
  1410. #undef URGENT_LOG
  1411. #endif