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.

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