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.

1512 lines
31 KiB

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