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.

1514 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 = {};
  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 (size_t 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 (size_t 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 (size_t 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. CSTR tV = RetVal;
  600. sprintf(RetVal, "%s%s%s", tV, S_Str, (*Data).at(i));
  601. };
  602. };
  603. return RetVal;
  604. }
  605. int getIP4(if_info ** arrParam, int max_ifs)
  606. {
  607. int index = 0;
  608. #ifdef __linux__
  609. struct ifaddrs *addrs, *tmp;
  610. getifaddrs(&addrs);
  611. tmp = addrs;
  612. // arrParam= malloc( 10 * sezeof(if_info) );
  613. while (tmp)
  614. {
  615. if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET)
  616. {
  617. if (strncmp(tmp->ifa_name, "lo", 2) != 0)
  618. {
  619. (*arrParam)[index].if_name = (CSTR) malloc(strlen(tmp->ifa_name) + 1);
  620. snprintf((*arrParam)[index].if_name, strlen(tmp->ifa_name) + 1, "%s", tmp->ifa_name);
  621. (*arrParam)[index].if_addr = (CSTR) malloc(16);
  622. struct sockaddr_in * pAddr = (struct sockaddr_in *) tmp->ifa_addr;
  623. snprintf((*arrParam)[index].if_addr, 16, "%s", inet_ntoa(pAddr->sin_addr));
  624. index++;
  625. if (index == max_ifs)
  626. {
  627. break;
  628. }
  629. }
  630. };
  631. tmp = tmp->ifa_next;
  632. };
  633. freeifaddrs(addrs);
  634. #endif
  635. return index;
  636. }
  637. #ifdef __linux__
  638. long long getFreeSpace(CSTR DirName)
  639. {
  640. struct statvfs fiData;
  641. if ((statvfs(DirName, &fiData)) < 0)
  642. {
  643. return -1;
  644. };
  645. return fiData.f_bsize * fiData.f_bfree;
  646. }
  647. long long getTotalSpace(CSTR DirName)
  648. {
  649. struct statvfs fiData;
  650. if ((statvfs(DirName, &fiData)) < 0)
  651. {
  652. return -1;
  653. };
  654. return fiData.f_bsize * fiData.f_blocks;
  655. }
  656. #else
  657. __int64 getFreeSpace(CSTR DirName)
  658. {
  659. return -1;
  660. }
  661. __int64 getTotalSpace(CSTR DirName)
  662. {
  663. return -1;
  664. }
  665. #endif
  666. CSTR getTStr(CSTR Fmt)
  667. {
  668. // CSTR RetVal = NULL;
  669. char DateStr[200];
  670. time_t t;
  671. struct tm * tmp;
  672. t = time(NULL);
  673. tmp = gmtime(&t);
  674. if (tmp == NULL)
  675. {
  676. fprintf(stderr, "localtime!");
  677. return NULL;
  678. };
  679. if (Fmt == NULL)
  680. {
  681. if (strftime(DateStr, 200, "%F %T GMT", tmp) == 0)
  682. {
  683. fprintf(stderr, "strftime returned 0");
  684. return NULL;
  685. };
  686. }
  687. else
  688. {
  689. if (strftime(DateStr, 200, Fmt, tmp) == 0)
  690. {
  691. fprintf(stderr, "strftime returned 0");
  692. return NULL;
  693. };
  694. }
  695. // RetVal =(CSTR) malloc( strlen(DateStr) +1 );
  696. // if( RetVal != NULL ) strcpy( RetVal, DateStr );
  697. #ifdef __linux__
  698. return strdup(DateStr);
  699. #else
  700. return _strdup(DateStr);
  701. #endif
  702. }
  703. #ifdef __linux__
  704. int xioctl(int fh, unsigned long request, void * arg)
  705. {
  706. int r;
  707. do
  708. {
  709. r = ioctl(fh, request, arg);
  710. }
  711. while (-1 == r && EINTR == errno);
  712. return r;
  713. }
  714. uint64_t getMilliseconds(void)
  715. {
  716. uint64_t tMilliseconds = (uint64_t) 0;
  717. struct timeval tData;
  718. struct timezone tTZ;
  719. tTZ.tz_minuteswest = 0;
  720. tTZ.tz_dsttime = 0;
  721. if( gettimeofday( &tData, &tTZ ) == -1 ){
  722. tMilliseconds = (uint64_t) 0;
  723. #ifdef DEBUG
  724. URGENT_LOG("gettimeofday error!");
  725. #endif
  726. } else {
  727. tMilliseconds = (uint64_t) ( tData.tv_sec - ( tTZ.tz_minuteswest * 60 ) ); //Correcting TZ shift
  728. tMilliseconds = (tMilliseconds * 1000);
  729. tMilliseconds += (uint64_t) (tData.tv_usec / 1000);
  730. };
  731. return tMilliseconds;
  732. }
  733. #else // !__linux__
  734. #include <ctime>
  735. unsigned __int64 getMilliseconds(void)
  736. {
  737. unsigned __int64 tMilliseconds;
  738. SYSTEMTIME time;
  739. GetSystemTime(&time);
  740. tMilliseconds = (uint32_t) std::time(NULL);
  741. tMilliseconds *= 1000;
  742. tMilliseconds += time.wMilliseconds;
  743. return tMilliseconds;
  744. }
  745. #endif
  746. #ifdef __linux__
  747. #ifndef USE_SYSTEM_CALL_TO_PING
  748. #include <netinet/ip_icmp.h>
  749. // Define the Packet Constants
  750. // ping packet size
  751. #define PING_PKT_S 64
  752. // Automatic port number
  753. #define PORT_NO 0
  754. // Automatic port number
  755. #define PING_SLEEP_RATE 1000000
  756. // Gives the timeout delay for receiving packets
  757. // in seconds
  758. #define RECV_TIMEOUT 1
  759. // ping packet structure
  760. struct ping_pkt
  761. {
  762. struct icmphdr hdr;
  763. char msg[PING_PKT_S - sizeof(struct icmphdr)];
  764. };
  765. #endif //! USE_SYSTEM_CALL_TO_PING
  766. bool pingIP4(CSTR ip4)
  767. {
  768. #ifdef USE_SYSTEM_CALL_TO_PING
  769. // Ping google.com once, redirect output to /dev/null, and check the return value
  770. char tB[256];
  771. sprintf(tB, "ping -c 1 %s > /dev/null 2>&1", ip4);
  772. if (system(tB) == 0)
  773. {
  774. return true;
  775. }
  776. return false;
  777. #else // !USE_SYSTEM_CALL_TO_PING
  778. bool RetVal = false;
  779. if (ip4 == NULL)
  780. {
  781. return false;
  782. }
  783. if (strlen(ip4) < 7)
  784. {
  785. return false;
  786. }
  787. #ifdef DEBUG_EXTRA
  788. URGENT_LOG("Pinging Device!");
  789. #endif
  790. int sockfd;
  791. int ttl_val = 64, msg_count = 0, i, flag = 1, msg_received_count = 0;
  792. struct ping_pkt pckt;
  793. struct sockaddr_in ping_addr;
  794. struct sockaddr_in r_addr;
  795. struct timeval tv_out;
  796. tv_out.tv_sec = 0;
  797. tv_out.tv_usec = 300000; // 1/3 of second
  798. ping_addr.sin_family = AF_INET;
  799. ping_addr.sin_addr.s_addr = inet_addr(ip4);
  800. // ping_addr.sin_port = htons( m_nPort );
  801. #ifdef DEBUG_EXTRA
  802. URGENT_LOG(ip4);
  803. #endif
  804. sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  805. if (sockfd < 0)
  806. {
  807. URGENT_LOG("Socket file descriptor not received!");
  808. return false;
  809. };
  810. // set socket options at ip to TTL and value to 64,
  811. // change to what you want by setting ttl_val
  812. if (setsockopt(sockfd, SOL_IP, IP_TTL, &ttl_val, sizeof(ttl_val)) != 0)
  813. {
  814. URGENT_LOG("Setting socket options to TTL failed!");
  815. shutdown(sockfd, SHUT_RDWR);
  816. return false;
  817. };
  818. // setting timeout of recv setting
  819. setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char *) &tv_out, sizeof tv_out);
  820. // flag is whether packet was sent or not
  821. flag = 1;
  822. // filling packet
  823. bzero(&pckt, sizeof(pckt));
  824. pckt.hdr.type = ICMP_ECHO;
  825. pckt.hdr.un.echo.id = getpid();
  826. for (i = 0; i < sizeof(pckt.msg) - 1; i++)
  827. {
  828. pckt.msg[i] = i + '0';
  829. }
  830. pckt.msg[i] = 0;
  831. pckt.hdr.un.echo.sequence = msg_count++;
  832. pckt.hdr.checksum = checksumPing(&pckt, sizeof(pckt));
  833. // SLEEP( 300 );
  834. // send packet
  835. if (sendto(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &ping_addr, sizeof(ping_addr)) <= 0)
  836. {
  837. URGENT_LOG("Packet Sending Failed!");
  838. shutdown(sockfd, SHUT_RDWR);
  839. return false;
  840. };
  841. // receive packet
  842. socklen_t addr_len = sizeof(r_addr);
  843. if (recvfrom(sockfd, &pckt, sizeof(pckt), 0, (struct sockaddr *) &r_addr, &addr_len) <= 0)
  844. {
  845. #ifdef DEBUG_EXTRA
  846. URGENT_LOG("Packet receive failed!");
  847. #endif
  848. }
  849. else
  850. {
  851. #ifdef DEBUG_EXTRA
  852. URGENT_LOG("Device pinged Sucessfully");
  853. #endif
  854. RetVal = true;
  855. };
  856. shutdown(sockfd, SHUT_RDWR);
  857. return RetVal;
  858. #endif //! USE_SYSTEM_CALL_TO_PING
  859. }
  860. bool enumerateDevices(enumeratorInfo * mlist, const char * dTemplate)
  861. {
  862. DIR * d;
  863. struct dirent * dir;
  864. DeviceInfo * tDevInfo;
  865. if (mlist == NULL)
  866. {
  867. return false;
  868. }
  869. if (dTemplate == NULL)
  870. {
  871. return false;
  872. }
  873. for (size_t i = 0; i < mlist->size(); i++)
  874. {
  875. delete(mlist->at(i));
  876. };
  877. mlist->clear();
  878. d = opendir("/dev");
  879. if (d)
  880. {
  881. while ((dir = readdir(d)) != NULL)
  882. {
  883. if (dir->d_type == DT_CHR || dir->d_type == DT_BLK)
  884. {
  885. if (strncmp(dir->d_name, dTemplate, 5) == 0)
  886. {
  887. tDevInfo = (DeviceInfo *) malloc(sizeof(DeviceInfo));
  888. sprintf(tDevInfo->DevicePath, "/dev/%s", dir->d_name);
  889. tDevInfo->FriendlyName[0] = (char) 0;
  890. if (strncmp(dTemplate, "video", 5) == 0)
  891. {
  892. FILE * fd;
  893. char CMD[1100];
  894. sprintf(CMD, "v4l2-ctl -d %s -D", tDevInfo->DevicePath);
  895. fd = popen(CMD, "r");
  896. if (fd != NULL)
  897. {
  898. char * line = NULL;
  899. size_t len = 0;
  900. ssize_t rd;
  901. while ((rd = getline(&line, &len, fd)) != -1)
  902. {
  903. char *tS1, *tS2;
  904. // Future use strcasestr() or make both stings same case
  905. if ((tS1 = strstr(line, "Bus info")) != NULL)
  906. {
  907. tS2 = trim(strstr(tS1, ":") + 2);
  908. sprintf(tDevInfo->FriendlyName, "%s", tS2);
  909. };
  910. };
  911. fclose(fd);
  912. if (line)
  913. {
  914. free(line);
  915. }
  916. };
  917. };
  918. mlist->push_back(tDevInfo);
  919. // printf("%s\n", dir->d_name );
  920. };
  921. // if( strncmp( dir->d_name, "ttyS", 4 ) == 0 ){
  922. // tBuffer = ( char * ) malloc( strlen(dir->d_name)+1 );
  923. // strncpy( tBuffer, dir->d_name, strlen(dir->d_name)+1 );
  924. // mlist->pushBack( tBuffer );
  925. // //printf("%s\n", dir->d_name );
  926. // };
  927. };
  928. };
  929. closedir(d);
  930. }
  931. else
  932. {
  933. return false;
  934. };
  935. return true;
  936. }
  937. #else
  938. #ifndef IID_PPV_ARGS
  939. extern "C++"
  940. {
  941. template <typename T> void ** IID_PPV_ARGS_Helper(T ** pp)
  942. {
  943. // make sure everyone derives from IUnknown
  944. static_cast<IUnknown *>(*pp);
  945. return reinterpret_cast<void **>(pp);
  946. }
  947. }
  948. #define IID_PPV_ARGS(ppType) __uuidof(**(ppType)), IID_PPV_ARGS_Helper(ppType)
  949. #endif
  950. #pragma comment(lib, "Strmiids.lib")
  951. bool enumerateDevices(enumeratorInfo * mlist, REFGUID category)
  952. {
  953. HRESULT hr;
  954. bool initOk = true;
  955. hr = CoInitializeEx(NULL, COINIT_SPEED_OVER_MEMORY | COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
  956. if (hr == E_INVALIDARG)
  957. {
  958. printf("Couldn't Init! hr=0x%x", hr);
  959. return false;
  960. }
  961. else if (hr == E_OUTOFMEMORY)
  962. {
  963. printf("Couldn't Init! hr=0x%x", hr);
  964. return false;
  965. }
  966. else if (hr == E_UNEXPECTED)
  967. {
  968. printf("Couldn't Init! hr=0x%x", hr);
  969. return false;
  970. }
  971. else if (hr == RPC_E_CHANGED_MODE)
  972. {
  973. initOk = false;
  974. };
  975. if (hr == S_OK || hr == RPC_E_CHANGED_MODE)
  976. {
  977. // Create the system device enumerator
  978. ICreateDevEnum * pDevEnum;
  979. hr = CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum));
  980. if (hr != S_OK)
  981. {
  982. printf("Couldn't create system enumerator! hr=0x%x", hr);
  983. CoUninitialize();
  984. return false;
  985. };
  986. if (pDevEnum != NULL)
  987. {
  988. IEnumMoniker * pClsEnum = NULL;
  989. hr = pDevEnum->CreateClassEnumerator(category, &pClsEnum, 0);
  990. if (hr == S_FALSE)
  991. {
  992. // The category is empty. Treat as an error.
  993. pDevEnum->Release();
  994. CoUninitialize();
  995. return false;
  996. };
  997. if (pClsEnum != NULL)
  998. {
  999. IMoniker * pMoniker = NULL;
  1000. while (pClsEnum->Next(1, &pMoniker, NULL) == S_OK)
  1001. {
  1002. IPropertyBag * pPropBag = NULL;
  1003. hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
  1004. if (FAILED(hr))
  1005. {
  1006. pMoniker->Release();
  1007. continue;
  1008. };
  1009. VARIANT var;
  1010. VariantInit(&var);
  1011. DeviceInfo * tRec;
  1012. tRec = (DeviceInfo *) malloc(sizeof(DeviceInfo));
  1013. // Get description or friendly name.
  1014. hr = pPropBag->Read(L"Description", &var, 0);
  1015. if (FAILED(hr))
  1016. {
  1017. hr = pPropBag->Read(L"FriendlyName", &var, 0);
  1018. };
  1019. if (SUCCEEDED(hr))
  1020. {
  1021. if (tRec != NULL)
  1022. {
  1023. sprintf(tRec->FriendlyName, "%S", var.bstrVal);
  1024. mlist->push_back(tRec);
  1025. };
  1026. VariantClear(&var);
  1027. };
  1028. hr = pPropBag->Write(L"FriendlyName", &var);
  1029. // WaveInID applies only to audio capture devices.
  1030. hr = pPropBag->Read(L"WaveInID", &var, 0);
  1031. if (SUCCEEDED(hr))
  1032. {
  1033. // printf("WaveIn ID: %d\n", var.lVal);
  1034. VariantClear(&var);
  1035. };
  1036. hr = pPropBag->Read(L"DevicePath", &var, 0);
  1037. if (SUCCEEDED(hr))
  1038. {
  1039. // The device path is not intended for display.
  1040. if (tRec != NULL)
  1041. {
  1042. sprintf(tRec->DevicePath, "%S", var.bstrVal);
  1043. };
  1044. VariantClear(&var);
  1045. };
  1046. pPropBag->Release();
  1047. pMoniker->Release();
  1048. };
  1049. pClsEnum->Release();
  1050. };
  1051. pDevEnum->Release();
  1052. };
  1053. if (initOk)
  1054. {
  1055. CoUninitialize();
  1056. }
  1057. };
  1058. return true;
  1059. }
  1060. #endif
  1061. size_t escape_string(char * to, size_t to_length, const char * from, size_t length)
  1062. {
  1063. const char * to_start = to;
  1064. const char * end, *to_end = to_start + (to_length ? to_length - 1 : 2 * length);
  1065. bool overflow = false;
  1066. for (end = from + length; from < end; from++)
  1067. {
  1068. char escape = 0;
  1069. int tmp_length;
  1070. /*
  1071. If the next character appears to begin a multi-byte character, we
  1072. escape that first byte of that apparent multi-byte character. (The
  1073. character just looks like a multi-byte character -- if it were actually
  1074. a multi-byte character, it would have been passed through in the test
  1075. above.)
  1076. Without this check, we can create a problem by converting an invalid
  1077. multi-byte character into a valid one. For example, 0xbf27 is not
  1078. a valid GBK character, but 0xbf5c is. (0x27 = ', 0x5c = \)
  1079. */
  1080. tmp_length = 0;
  1081. if (tmp_length > 1)
  1082. {
  1083. escape = *from;
  1084. }
  1085. else
  1086. {
  1087. switch (*from)
  1088. {
  1089. case 0 : /* Must be escaped for 'mysql' */ escape = '0'; break;
  1090. case '\n' : /* Must be escaped for logs */ escape = 'n'; break;
  1091. case '\r' : escape = 'r'; break;
  1092. case '\\' : escape = '\\'; break;
  1093. case '\'' : escape = '\''; break;
  1094. case '"' : /* Better safe than sorry */ escape = '"'; break;
  1095. case '\032': /* This gives problems on Win32 */ escape = 'Z'; break;
  1096. };
  1097. };
  1098. if (escape)
  1099. {
  1100. if (to + 2 > to_end)
  1101. {
  1102. overflow = true;
  1103. break;
  1104. };
  1105. *to++ = '\\';
  1106. *to++ = escape;
  1107. }
  1108. else
  1109. {
  1110. if (to + 1 > to_end)
  1111. {
  1112. overflow = true;
  1113. break;
  1114. };
  1115. *to++ = *from;
  1116. };
  1117. };
  1118. *to = 0;
  1119. return overflow ? (size_t) -1 : (size_t) (to - to_start);
  1120. }
  1121. /* Read characters from 'fd' until a newline is encountered. If a newline
  1122. character is not encountered in the first (n - 1) bytes, then the excess
  1123. characters are discarded. The returned string placed in 'buf' is
  1124. null-terminated and includes the newline character if it was read in the
  1125. first (n - 1) bytes. The function return value is the number of bytes
  1126. placed in buffer (which includes the newline character if encountered,
  1127. but excludes the terminating null byte). */
  1128. ssize_t readLine(int fd, char * buffer, size_t n)
  1129. {
  1130. ssize_t numRead; /* # of bytes fetched by last read() */
  1131. size_t totRead; /* Total bytes read so far */
  1132. char * buf;
  1133. char ch;
  1134. if (n <= 0 || buffer == NULL)
  1135. {
  1136. errno = EINVAL;
  1137. return -1;
  1138. }
  1139. buf = buffer; /* No pointer arithmetic on "void *" */
  1140. totRead = 0;
  1141. for (;;)
  1142. {
  1143. numRead = read(fd, &ch, 1);
  1144. if (numRead == -1)
  1145. {
  1146. if (errno == EINTR) /* Interrupted --> restart read() */
  1147. {
  1148. continue;
  1149. }
  1150. else
  1151. {
  1152. return -1; /* Some other error */
  1153. }
  1154. }
  1155. else if (numRead == 0)
  1156. { /* EOF */
  1157. if (totRead == 0) /* No bytes read; return 0 */
  1158. {
  1159. return 0;
  1160. }
  1161. else /* Some bytes read; add '\0' */
  1162. {
  1163. break;
  1164. }
  1165. }
  1166. else
  1167. { /* 'numRead' must be 1 if we get here */
  1168. if (totRead < n - 1)
  1169. { /* Discard > (n - 1) bytes */
  1170. totRead++;
  1171. *buf++ = ch;
  1172. }
  1173. if (ch == '\n')
  1174. {
  1175. break;
  1176. }
  1177. }
  1178. }
  1179. *buf = '\0';
  1180. return totRead;
  1181. }
  1182. ssize_t readLine(FILE * fd, char * buffer, size_t n)
  1183. {
  1184. ssize_t numRead; /* # of bytes fetched by last read() */
  1185. size_t totRead; /* Total bytes read so far */
  1186. char * buf;
  1187. char ch;
  1188. if (n <= 0 || buffer == NULL)
  1189. {
  1190. errno = EINVAL;
  1191. return -1;
  1192. }
  1193. buf = buffer; /* No pointer arithmetic on "void *" */
  1194. totRead = 0;
  1195. for (;;)
  1196. {
  1197. numRead = fread(&ch, 1, 1, fd);
  1198. if (numRead == -1)
  1199. {
  1200. if (errno == EINTR) /* Interrupted --> restart read() */
  1201. {
  1202. continue;
  1203. }
  1204. else
  1205. {
  1206. return -1; /* Some other error */
  1207. }
  1208. }
  1209. else if (numRead == 0)
  1210. { /* EOF */
  1211. if (totRead == 0) /* No bytes read; return 0 */
  1212. {
  1213. return 0;
  1214. }
  1215. else /* Some bytes read; add '\0' */
  1216. {
  1217. break;
  1218. }
  1219. }
  1220. else
  1221. { /* 'numRead' must be 1 if we get here */
  1222. if (totRead < n - 1)
  1223. { /* Discard > (n - 1) bytes */
  1224. totRead++;
  1225. *buf++ = ch;
  1226. }
  1227. if (ch == '\n')
  1228. {
  1229. break;
  1230. }
  1231. }
  1232. }
  1233. *buf = '\0';
  1234. return totRead;
  1235. }
  1236. localIpAddresses g_vLocalIpAdressess;
  1237. bool g_bAdressesAreDiscovered = false;
  1238. #ifdef __linux__
  1239. bool isProcessUniq(CSTR pName)
  1240. {
  1241. char tB[256];
  1242. FILE * fd;
  1243. sprintf(tB, "pidof %s", pName);
  1244. fd = popen(tB, "r");
  1245. if (fd)
  1246. {
  1247. int rs = readLine(fd, tB, 256);
  1248. if (rs > 2)
  1249. {
  1250. fclose(fd);
  1251. return false;
  1252. };
  1253. fclose(fd);
  1254. };
  1255. return true;
  1256. }
  1257. #include <linux/if.h>
  1258. localIpAddresses * getLocalIP()
  1259. {
  1260. // Check for Filter LO and TUN Devices!
  1261. if (! g_bAdressesAreDiscovered)
  1262. {
  1263. struct ifaddrs *ifaddr, *ifa;
  1264. localIp4Info * tIpAddress = NULL;
  1265. if (getifaddrs(&ifaddr) != -1)
  1266. {
  1267. /* Walk through linked list, maintaining head pointer so we can free list later */
  1268. for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
  1269. {
  1270. // Filter Loopback if
  1271. if (strstr(ifa->ifa_name, "lo") != NULL)
  1272. {
  1273. continue;
  1274. }
  1275. // Filter vpn TUN if
  1276. if (strstr(ifa->ifa_name, "tun") != NULL)
  1277. {
  1278. continue;
  1279. }
  1280. //char protocol[IFNAMSIZ] = {0};
  1281. if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
  1282. {
  1283. continue;
  1284. }
  1285. tIpAddress = (localIp4Info *) malloc(sizeof(localIp4Info));
  1286. if (tIpAddress != NULL)
  1287. {
  1288. 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]);
  1289. 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]);
  1290. 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],
  1291. (uint8_t) ifa->ifa_ifu.ifu_broadaddr->sa_data[5]);
  1292. g_vLocalIpAdressess.push_back(tIpAddress);
  1293. };
  1294. };
  1295. freeifaddrs(ifaddr);
  1296. };
  1297. g_bAdressesAreDiscovered = true;
  1298. };
  1299. return &g_vLocalIpAdressess;
  1300. }
  1301. #else // !linux
  1302. // https://stackoverflow.com/questions/5213629/how-to-enumerate-all-available-network-interfaces
  1303. #include <iphlpapi.h>
  1304. #pragma comment(lib, "IPHLPAPI.lib")
  1305. localIpAddresses * getLocalIP()
  1306. {
  1307. char psBuffer[128];
  1308. FILE * fd;
  1309. BYTE mB;
  1310. localIp4Info * tIpAddress;
  1311. if (! g_bAdressesAreDiscovered)
  1312. {
  1313. ULONG outBufLen = 0;
  1314. DWORD dwRetVal = 0;
  1315. IP_ADAPTER_INFO * pAdapterInfos = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO));
  1316. // retry up to 5 times, to get the adapter infos needed
  1317. for (int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i)
  1318. {
  1319. dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen);
  1320. if (dwRetVal == NO_ERROR)
  1321. {
  1322. break;
  1323. }
  1324. else
  1325. {
  1326. if (dwRetVal == ERROR_BUFFER_OVERFLOW)
  1327. {
  1328. free(pAdapterInfos);
  1329. pAdapterInfos = (IP_ADAPTER_INFO *) malloc(outBufLen);
  1330. }
  1331. else
  1332. {
  1333. // pAdapterInfos = 0;
  1334. break;
  1335. };
  1336. };
  1337. };
  1338. if (dwRetVal == NO_ERROR)
  1339. {
  1340. IP_ADAPTER_INFO * pAdapterInfo = pAdapterInfos;
  1341. while (pAdapterInfo)
  1342. {
  1343. IP_ADDR_STRING * pIpAddress = &(pAdapterInfo->IpAddressList);
  1344. while (pIpAddress != 0)
  1345. {
  1346. uint8_t A, B, C, D;
  1347. uint8_t M, O, S, K, G, U, T, E;
  1348. uint32_t Z1, Z2, Z3, Z4;
  1349. int RetVal;
  1350. RetVal = sscanf(pIpAddress->IpAddress.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  1351. A = Z1 & 0xFF;
  1352. B = Z2 & 0xFF;
  1353. C = Z3 & 0xFF;
  1354. D = Z4 & 0xFF;
  1355. RetVal = sscanf(pIpAddress->IpMask.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  1356. M = Z1 & 0xFF;
  1357. O = Z2 & 0xFF;
  1358. S = Z3 & 0xFF;
  1359. K = Z4 & 0xFF;
  1360. //
  1361. // <<<<
  1362. // here pAdapterInfo->Address should contain the MAC address
  1363. // >>>>
  1364. //
  1365. if (A > 0)
  1366. {
  1367. tIpAddress = (localIp4Info *) malloc(sizeof(localIp4Info));
  1368. if (tIpAddress != NULL)
  1369. {
  1370. sprintf(tIpAddress->address, "%d.%d.%d.%d", A, B, C, D);
  1371. sprintf(tIpAddress->netmask, "%d.%d.%d.%d", M, O, S, K);
  1372. G = (A & M) | (~M);
  1373. U = (B & O) | (~O);
  1374. T = (C & S) | (~S);
  1375. E = (D & K) | (~K);
  1376. sprintf(tIpAddress->broadcast, "%d.%d.%d.%d", G, U, T, E);
  1377. g_vLocalIpAdressess.push_back(tIpAddress);
  1378. };
  1379. };
  1380. pIpAddress = pIpAddress->Next;
  1381. };
  1382. pAdapterInfo = pAdapterInfo->Next;
  1383. };
  1384. };
  1385. free(pAdapterInfos);
  1386. };
  1387. return &g_vLocalIpAdressess;
  1388. }
  1389. #endif
  1390. #ifdef DEBUG
  1391. #undef URGENT_LOG
  1392. #endif