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.

1127 lines
32 KiB

7 years ago
​
​
6 years ago
7 years ago
6 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
6 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
3 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
7 years ago
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
6 years ago
7 years ago
​
​
​
​
​
​
6 years ago
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
6 years ago
6 years ago
6 years ago
​
​
7 years ago
​
​
​
​
​
​
​
​
​
5 years ago
​
7 years ago
​
​
​
​
5 years ago
7 years ago
5 years ago
7 years ago
5 years ago
7 years ago
​
7 years ago
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
​
​
7 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
7 years ago
7 years ago
​
7 years ago
​
​
7 years ago
6 years ago
6 years ago
7 years ago
  1. #include "basicFunctionality.h"
  2. #include "../../alg/generic/md5.h"
  3. #include <sys/ioctl.h>
  4. //#include <sys/sendfile.h>
  5. #ifdef DEBUG
  6. #include "basicLogCollection.h"
  7. #define URGENT_LOG(X) basicLogCollection::getInstance()->Log("basic Functionality", NULL, X )
  8. #endif
  9. #ifdef __linux__
  10. int ch_chown( const char *file_path, const char *user_name, const char *group_name){
  11. uid_t uid;
  12. gid_t gid;
  13. struct passwd *pwd;
  14. struct group *grp;
  15. pwd = getpwnam(user_name);
  16. if (pwd == NULL) {
  17. #ifdef DEBUG
  18. URGENT_LOG("Failed to get uid!");
  19. #endif
  20. return -1;
  21. };
  22. uid = pwd->pw_uid;
  23. grp = getgrnam(group_name);
  24. if (grp == NULL){
  25. #ifdef DEBUG
  26. URGENT_LOG("Failed to get gid!");
  27. #endif
  28. return -1;
  29. };
  30. gid = grp->gr_gid;
  31. return chown(file_path, uid, gid);
  32. };
  33. #endif
  34. int checkCmdExists( CSTR cmd ){
  35. FILE * fd = popen( cmd, "r" );
  36. char tB[1024];
  37. int rVal = -1;
  38. if( fd!= NULL ){
  39. while ( !feof(fd)) {
  40. fgets((CSTR)tB, 1024, fd );
  41. trim( tB );
  42. if( strstr(tB, "command not found" ) != NULL){
  43. rVal = 0;
  44. break;
  45. };
  46. };
  47. if( rVal < 1 ) rVal = 1;
  48. fclose(fd);
  49. };
  50. return rVal;
  51. };
  52. uid_t getUserUid( CSTR uname ){
  53. struct passwd *pwd;
  54. if ( uname == NULL ) return -1;
  55. pwd = getpwnam( uname ); /* Try getting UID for username */
  56. if (pwd == NULL) return -1;
  57. return pwd->pw_uid;
  58. };
  59. gid_t getUserGid( CSTR uname ){
  60. struct passwd *pwd;
  61. if ( uname == NULL ) return -1;
  62. pwd = getpwnam( uname ); /* Try getting GID for username */
  63. if (pwd == NULL) return -1;
  64. return pwd->pw_gid;
  65. };
  66. bool createAccessibleDir( CSTR path, mode_t mode, uid_t uid, gid_t gid ){
  67. if( mkdir( path, mode ) != 0 ) return false;
  68. chown( path, uid, gid );
  69. return true;
  70. };
  71. #ifdef __linux__
  72. int fileCopy( const char* source, const char* destination ){
  73. int input, output;
  74. if ((input = open(source, O_RDONLY)) == -1) return -1;
  75. if ((output = creat(destination, 0660)) == -1){
  76. close(input);
  77. return -1;
  78. };
  79. //Here we use kernel-space copying for performance reasons
  80. #if defined(__APPLE__) || defined(__FreeBSD__)
  81. //fcopyfile works on FreeBSD and OS X 10.5+
  82. int result = fcopyfile(input, output, 0, COPYFILE_ALL);
  83. #else
  84. //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
  85. off_t bytesCopied = 0;
  86. struct stat fileinfo = {0};
  87. fstat(input, &fileinfo);
  88. int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
  89. #endif
  90. close(input);
  91. close(output);
  92. return result;
  93. };
  94. #endif
  95. bool fileExist(const char *strFilename) {
  96. struct stat stFileInfo;
  97. int intStat;
  98. intStat = stat( strFilename ,&stFileInfo);
  99. if( intStat == 0 ){
  100. return true;
  101. };
  102. return false;
  103. };
  104. bool dirEmpty( const char *dirname ){
  105. int n = 0;
  106. struct dirent *d;
  107. DIR *dir = opendir(dirname);
  108. if( dir == NULL) return true;
  109. while( (d = readdir(dir)) != NULL )if( ++n > 2 ) break;
  110. closedir( dir );
  111. if( n <= 2 ) return true;
  112. return false;
  113. };
  114. #ifndef __linux__
  115. #else
  116. #include <sys/types.h>
  117. #include <unistd.h>
  118. #include <sys/syscall.h>
  119. #include <sys/types.h>
  120. pid_t gettid( void ){
  121. return syscall(SYS_gettid);
  122. };
  123. #endif
  124. const char *__BuildDate = (__DATE__);
  125. const char *__BuildTime = (__TIME__);
  126. const char *__BuildTS = (__TIMESTAMP__);
  127. CSTR getBuildID( void ){
  128. return NULL;
  129. };
  130. /* Global Time Diff Value to correct Timestamps */
  131. static int g_iTimeDiff = 0;
  132. /**
  133. * number of seconds from 1 Jan. 1601 00:00 to 1 Jan 1970 00:00 UTC
  134. */
  135. // Defined in Header File
  136. //#define EPOCH_DIFF 11644473600LL
  137. //#define UNIX_TimeStamp_2_WINDOWS_FileTime_SHIFT 116444736000000000
  138. bool correctSysTime( int diff ){
  139. #ifdef __linux__
  140. struct timeval tData;
  141. struct timezone tTZ;
  142. tTZ.tz_minuteswest = 0;
  143. tTZ.tz_dsttime = 0;
  144. if( gettimeofday( &tData, &tTZ ) == -1 ){
  145. return false;
  146. } else {
  147. tData.tv_sec += diff / 1000;
  148. tData.tv_usec += ( diff * 1000 ) % 1000000;
  149. };
  150. if( settimeofday( &tData, &tTZ ) == -1 ){
  151. return false;
  152. };
  153. #else
  154. unsigned __int64 tMilliseconds;
  155. SYSTEMTIME Ztime;
  156. GetSystemTime(&Ztime);
  157. SystemTimeToFileTime( &Ztime, (FILETIME*) &tMilliseconds );
  158. tMilliseconds += diff * 10000;
  159. FileTimeToSystemTime( (FILETIME*) &tMilliseconds, &Ztime );
  160. if( 0 == SetSystemTime(&Ztime) ) return false;
  161. #endif
  162. return true;
  163. };
  164. off_t getFileSize(const char *filename) {
  165. struct stat st;
  166. if( stat(filename, &st) == 0 ) return st.st_size;
  167. return -1;
  168. };
  169. bool correctSoftTime( int diff ){
  170. g_iTimeDiff = diff;
  171. return true;
  172. };
  173. #ifdef __linux__
  174. unsigned long long getTimeValue( void ){
  175. unsigned long long tMilliseconds;
  176. struct timeval tData;
  177. struct timezone tTZ;
  178. tMilliseconds = 0;
  179. tTZ.tz_minuteswest = 0;
  180. tTZ.tz_dsttime = 0;
  181. if( gettimeofday( &tData, &tTZ ) == -1 ){
  182. } else {
  183. tMilliseconds = tData.tv_sec;
  184. tMilliseconds = tMilliseconds *1000;
  185. tMilliseconds += tData.tv_usec / 1000;
  186. };
  187. #else
  188. /*
  189. void TimetToFileTime( time_t t, LPFILETIME pft ){
  190. LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
  191. pft->dwLowDateTime = (DWORD) ll;
  192. pft->dwHighDateTime = ll >>32;
  193. }*/
  194. unsigned __int64 getTimeValue( void ){
  195. unsigned __int64 tMilliseconds;
  196. SYSTEMTIME Ztime;
  197. GetSystemTime(&Ztime);
  198. SystemTimeToFileTime( &Ztime, (FILETIME*) &tMilliseconds );
  199. tMilliseconds -= UNIX_TimeStamp_2_WINDOWS_FileTime_SHIFT;
  200. tMilliseconds = tMilliseconds / 10000;
  201. #endif
  202. tMilliseconds += g_iTimeDiff;
  203. return tMilliseconds;
  204. };
  205. static uint32_t UID_INCREMENTAL_VALUE = 0;
  206. #define UID_INCREMEMTAL (UID_INCREMENTAL_VALUE++)
  207. CSTR getTimeStamp( void ){
  208. CSTR RetVal = NULL;
  209. time_t rawtime;
  210. uint32_t msec;
  211. struct tm * ptm = NULL;
  212. time ( &rawtime );
  213. ptm = gmtime ( &rawtime );
  214. msec = getTimeValue() % 1000;
  215. //2019-03-24T12:32:59.670Z
  216. if( ptm != NULL ) {
  217. RetVal = (CSTR) malloc( 128 );
  218. if( RetVal!=NULL ){
  219. sprintf( RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
  220. (ptm->tm_year+1900),
  221. (ptm->tm_mon+1),
  222. ptm->tm_mday,
  223. ptm->tm_hour,
  224. ptm->tm_min,
  225. ptm->tm_sec,
  226. msec
  227. );
  228. };
  229. };
  230. return RetVal;
  231. };
  232. CSTR getTimeStampI( void ){
  233. CSTR RetVal = NULL;
  234. time_t rawtime;
  235. uint32_t msec;
  236. struct tm * ptm = NULL;
  237. time ( &rawtime );
  238. ptm = gmtime ( &rawtime );
  239. msec = getTimeValue() % 1000;
  240. //2019-03-24T12:32:59.670Z
  241. if( ptm != NULL ) {
  242. RetVal = (CSTR) malloc( 128 );
  243. if( RetVal!=NULL ){
  244. sprintf( RetVal, "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ %d",
  245. (ptm->tm_year+1900),
  246. (ptm->tm_mon+1),
  247. ptm->tm_mday,
  248. ptm->tm_hour,
  249. ptm->tm_min,
  250. ptm->tm_sec,
  251. msec,
  252. UID_INCREMEMTAL
  253. );
  254. };
  255. };
  256. return RetVal;
  257. };
  258. CSTR getUniqID_MD5( void ){
  259. CSTR tVal = NULL;
  260. CSTR tMD5 = NULL;
  261. char buf[33];
  262. tVal = getTimeStampI();
  263. buf[0] = (char)0;
  264. if( tVal ){
  265. tMD5 = MD5String( tVal );
  266. if( tMD5 ) {
  267. sprintf( buf, "%s", tMD5 );
  268. free( tMD5 );
  269. };
  270. free( tVal );
  271. };
  272. #ifdef __linux__
  273. return strdup( buf );
  274. #else
  275. return _strdup( buf );
  276. #endif
  277. };
  278. CSTR getUniqID_SHA256(void){ return NULL;};
  279. int rand( int a, int b ){
  280. if( b > a ){
  281. return a + (rand() *( b - a )) / RAND_MAX;
  282. };
  283. return b + ( rand() * ( a - b )) / RAND_MAX;
  284. };
  285. CSTR getUniqID_UUID( uint32_t SEED ){
  286. /*
  287. char buf[46];
  288. if( SEED ) {
  289. srand( SEED );
  290. } else {
  291. srand( getMilliseconds() );// time(NULL) );
  292. };
  293. snprintf( buf, 42, "%8.8x-%4.4x-%4.4x-%4.4x-%6.6x%6.6x",
  294. rand() & 0xFFFFFFFF,
  295. rand() & 0xFFFF,
  296. (rand() & 0x0FFF) | 0x4000, // M 4 MSB version => version 4
  297. (rand() & 0x1FFF) | 0x8000, // N: 3 MSB variant => variant 1
  298. rand() & 0xFFFFFF, rand() & 0xFFFFFF
  299. );
  300. #ifdef __linux__
  301. return strdup( buf );
  302. #else
  303. return _strdup( buf );
  304. #endif
  305. */
  306. CSTR tVal = NULL;
  307. CSTR tMD5 = NULL;
  308. char buf[37];
  309. tVal = getTimeStamp();
  310. buf[0] = (char)0;
  311. if( tVal ){
  312. char tt[256];
  313. sprintf( tt, "%s %d %d", tVal ,SEED, UID_INCREMEMTAL );
  314. tMD5 = MD5String( tt );
  315. if( tMD5 ) {
  316. memcpy( buf, tMD5, 8 );
  317. buf[8] = '-';
  318. memcpy( buf+9, tMD5+8, 4 );
  319. buf[13] = '-';
  320. memcpy( buf+14, tMD5+12, 4 );
  321. buf[18] = '-';
  322. memcpy( buf+19, tMD5+16, 4 );
  323. buf[23] = '-';
  324. memcpy( buf+24, tMD5+20, 12 );
  325. buf[36] = (char)0;
  326. free( tMD5 );
  327. };
  328. free( tVal );
  329. };
  330. #ifdef __linux__
  331. return strdup( buf );
  332. #else
  333. return _strdup( buf );
  334. #endif
  335. };
  336. CSTR trim( CSTR val ){
  337. int i = 0;
  338. int j = strlen( val );
  339. if( j ){
  340. while(( i < j ) && (((unsigned char)val[i])< 0x21 )) i++;
  341. while(( j > i ) && (((unsigned char)val[j])< 0x21 )) j--;
  342. if( ( i > 0 ) && ((j-i+1) > 0 ) ) memcpy( val, val+i, j-i+1 );
  343. val[j-i+1]=(char)0;
  344. };
  345. return val;
  346. };
  347. // orig - input String to Search In
  348. // rep - token to search
  349. // with - replacement for token
  350. // in case with is NULL - cutting off the token
  351. // You must free the result if result is non-NULL.
  352. CSTR strReplace( CSTR orig, CSTR rep, CSTR with ){
  353. char *result; // the return string
  354. char *ins; // the next insert point
  355. char *tmp; // varies
  356. int len_rep; // length of rep (the string to remove)
  357. int len_with; // length of with (the string to replace rep with)
  358. int len_front; // distance between rep and end of last rep
  359. int count; // number of replacements
  360. // sanity checks and initialization
  361. if (!orig || !rep) return NULL;
  362. len_rep = strlen(rep);
  363. if (len_rep == 0) return NULL; // empty rep causes infinite loop during count
  364. if (!with) with =(CSTR)""; // In case With not suplied - just cut off Token
  365. len_with = strlen(with);
  366. // count the number of replacements needed
  367. ins = orig;
  368. for (count = 0; tmp = strstr(ins, rep); ++count) {
  369. ins = tmp + len_rep;
  370. }
  371. tmp = result = (CSTR) malloc(strlen(orig) + (len_with - len_rep) * count + 1);
  372. if( !result ) return NULL;
  373. // first time through the loop, all the variable are set correctly
  374. // from here on,
  375. // tmp points to the end of the result string
  376. // ins points to the next occurrence of rep in orig
  377. // orig points to the remainder of orig after "end of rep"
  378. while (count--) {
  379. ins = strstr(orig, rep);
  380. len_front = ins - orig;
  381. tmp = strncpy(tmp, orig, len_front) + len_front;
  382. tmp = strcpy(tmp, with) + len_with;
  383. orig += len_front + len_rep; // move to next "end of rep"
  384. }
  385. strcpy(tmp, orig);
  386. return result;
  387. };
  388. uint8_t checksum8( uint8_t *Buffer, size_t BufferSize ){
  389. uint16_t TempVal;
  390. TempVal = 0;
  391. for( int index = 0; index < BufferSize; index++ ) {
  392. TempVal+=Buffer[index];
  393. };
  394. return (uint8_t)(TempVal & 0x00FF);
  395. };
  396. uint16_t checksum16( uint8_t *Buffer, size_t BufferSize ){
  397. uint32_t TempVal;
  398. TempVal = 0;
  399. for( int index = 0; index < BufferSize; index++ ) {
  400. TempVal+=Buffer[index];
  401. };
  402. return (uint16_t)(TempVal & 0x0000FFFF);
  403. };
  404. uint8_t checksumLGS( uint8_t *Buffer, size_t BufferSize ){
  405. uint16_t TempVal;
  406. TempVal = 0;
  407. for( int index = 0; index < BufferSize; index++ ) {
  408. TempVal+=Buffer[index];
  409. };
  410. return (uint8_t)(TempVal & 0x00FF);
  411. };
  412. // Calculating the Check Sum for Ping package
  413. uint16_t checksumPing(void *b, size_t len){
  414. uint16_t *buf = (uint16_t *) b;
  415. uint32_t sum=0;
  416. uint16_t result;
  417. for ( sum = 0; len > 1; len -= 2 )
  418. sum += *buf++;
  419. if ( len == 1 )
  420. sum += *(unsigned char*)buf;
  421. sum = (sum >> 16) + (sum & 0xFFFF);
  422. sum += (sum >> 16);
  423. result = ~sum;
  424. return result;
  425. };
  426. CArray *explode( char Delim, CSTR S_Str ){
  427. bool ws = false;
  428. CArray * RetVal = NULL;
  429. CSTR b_ptr = S_Str;
  430. U16 s_ptr = 0;
  431. if( S_Str ){
  432. RetVal = new CArray;
  433. if( RetVal ){
  434. while ((U8)S_Str[s_ptr]) {
  435. if( (( U8 ) Delim ) == (( U8 )S_Str[s_ptr]) ){
  436. if (!ws) {
  437. ws = true;
  438. S_Str[s_ptr] = (char)0;
  439. RetVal->push_back( b_ptr );
  440. s_ptr++;
  441. b_ptr = &S_Str[s_ptr];
  442. } else s_ptr++;
  443. } else {
  444. ws = false;
  445. s_ptr++;
  446. };
  447. };
  448. RetVal->push_back( b_ptr );
  449. };
  450. };
  451. return RetVal;
  452. };
  453. CSTR implode( CArray *Data, CSTR S_Str, U8 Start, U8 End ){
  454. CSTR RetVal;
  455. U8 RStart = Start;
  456. U8 REnd = End;
  457. if( Start > Data->size() ) return NULL;
  458. if( End < Start ) return NULL;
  459. if( End > Data->size() ) REnd = (U8)(Data->size()-1);
  460. if( strlen( (*Data).at( RStart )) ){
  461. RetVal = (CSTR) malloc( strlen( (*Data).at( RStart )) + 1 );
  462. sprintf( RetVal,"%s",(*Data).at( RStart ));
  463. } else {
  464. RetVal = (CSTR) malloc( 1 );
  465. *RetVal=(char)0;
  466. };
  467. if (RetVal != NULL) {
  468. for (int i = RStart + 1; i < REnd; i++) {
  469. RetVal = (CSTR)realloc(RetVal, strlen(RetVal) + strlen((*Data).at(i)) + 1 + strlen(S_Str));
  470. sprintf(RetVal, "%s%s%s", RetVal, S_Str, (*Data).at(i));
  471. };
  472. };
  473. return RetVal;
  474. };
  475. int getIP4( if_info **arrParam, int max_ifs ){
  476. int index = 0;
  477. #ifdef __linux__
  478. struct ifaddrs *addrs, *tmp;
  479. getifaddrs(&addrs);
  480. tmp = addrs;
  481. //arrParam= malloc( 10 * sezeof(if_info) );
  482. while (tmp){
  483. if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET){
  484. if( strncmp( tmp->ifa_name, "lo", 2 ) != 0 ){
  485. (*arrParam)[index].if_name = (CSTR)malloc(strlen(tmp->ifa_name)+1);
  486. snprintf( (*arrParam)[index].if_name, strlen(tmp->ifa_name)+1,"%s", tmp->ifa_name );
  487. (*arrParam)[index].if_addr = (CSTR)malloc(16);
  488. struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
  489. snprintf( (*arrParam)[index].if_addr, 16, "%s", inet_ntoa(pAddr->sin_addr) );
  490. index++;
  491. if( index == max_ifs ) break;
  492. }
  493. };
  494. tmp = tmp->ifa_next;
  495. };
  496. freeifaddrs(addrs);
  497. #endif
  498. return index;
  499. };
  500. #ifdef __linux__
  501. long long getFreeSpace( CSTR DirName ){
  502. struct statvfs fiData;
  503. if( ( statvfs( DirName, &fiData ) ) < 0 ) {
  504. return -1;
  505. };
  506. return fiData.f_bsize * fiData.f_bfree;
  507. };
  508. long long getTotalSpace( CSTR DirName ){
  509. struct statvfs fiData;
  510. if( ( statvfs( DirName, &fiData ) ) < 0 ) {
  511. return -1;
  512. };
  513. return fiData.f_bsize * fiData.f_blocks;
  514. };
  515. #else
  516. __int64 getFreeSpace( CSTR DirName ){
  517. return -1;
  518. };
  519. __int64 getTotalSpace( CSTR DirName ){
  520. return -1;
  521. };
  522. #endif
  523. CSTR getTStr( CSTR Fmt ){
  524. //CSTR RetVal = NULL;
  525. char DateStr[200];
  526. time_t t;
  527. struct tm *tmp;
  528. t = time(NULL);
  529. tmp = gmtime(&t);
  530. if( tmp == NULL) {
  531. fprintf(stderr, "localtime!");
  532. return NULL;
  533. };
  534. if( Fmt == NULL ) {
  535. if( strftime( DateStr, 200, "%F %T GMT", tmp )==0 ){
  536. fprintf( stderr, "strftime returned 0" );
  537. return NULL;
  538. };
  539. } else {
  540. if( strftime( DateStr, 200, Fmt, tmp )==0 ){
  541. fprintf( stderr, "strftime returned 0" );
  542. return NULL;
  543. };
  544. }
  545. //RetVal =(CSTR) malloc( strlen(DateStr) +1 );
  546. //if( RetVal != NULL ) strcpy( RetVal, DateStr );
  547. #ifdef __linux__
  548. return strdup(DateStr);
  549. #else
  550. return _strdup(DateStr);
  551. #endif
  552. };
  553. #ifdef __linux__
  554. int xioctl(int fh, int request, void *arg){
  555. int r;
  556. do {
  557. r = ioctl( fh, request, arg );
  558. } while (-1 == r && EINTR == errno);
  559. return r;
  560. };
  561. uint64_t getMilliseconds( void ){
  562. uint64_t tMilliseconds = (uint64_t) 0;
  563. struct timeval tData;
  564. struct timezone tTZ;
  565. tTZ.tz_minuteswest = 0;
  566. tTZ.tz_dsttime = 0;
  567. if( gettimeofday( &tData, &tTZ ) == -1 ){
  568. tMilliseconds = (uint64_t) 0;
  569. #ifdef DEBUG
  570. URGENT_LOG( "EbioMat'!");
  571. #endif
  572. } else {
  573. tMilliseconds = (uint64_t) tData.tv_sec;
  574. tMilliseconds = ( tMilliseconds * 1000 );
  575. tMilliseconds += (uint64_t)( tData.tv_usec / 1000 );
  576. //URGENT_LOG("MilSecCollected!");
  577. };
  578. #else
  579. #include<ctime>
  580. unsigned __int64 getMilliseconds( void ){
  581. unsigned __int64 tMilliseconds;
  582. SYSTEMTIME time;
  583. GetSystemTime(&time);
  584. tMilliseconds = (uint32_t)std::time(NULL);
  585. tMilliseconds *= 1000;
  586. tMilliseconds += time.wMilliseconds;
  587. #endif
  588. return tMilliseconds;
  589. };
  590. #ifdef __linux__
  591. bool enumerateDevices( enumeratorInfo *mlist, const char *dTemplate){
  592. DIR *d;
  593. struct dirent *dir;
  594. DeviceInfo *tDevInfo;
  595. if( mlist == NULL )return false;
  596. if( dTemplate == NULL )return false;
  597. for( int i = 0; i < mlist->size(); i++ ) {
  598. delete( mlist->at(i) );
  599. };
  600. mlist->clear();
  601. d = opendir("/dev");
  602. if( d ){
  603. while((dir = readdir(d)) != NULL){
  604. if( dir->d_type == DT_CHR || dir->d_type == DT_BLK ){
  605. if( strncmp( dir->d_name, dTemplate, 5 ) == 0 ) {
  606. tDevInfo = (DeviceInfo *) malloc( sizeof(DeviceInfo) );
  607. sprintf( tDevInfo->DevicePath, "/dev/%s", dir->d_name );
  608. tDevInfo->FriendlyName[0] =(char)0;
  609. if( strncmp( dTemplate, "video", 5 ) == 0 ){
  610. FILE *fd;
  611. char CMD[256];
  612. sprintf( CMD, "v4l2-ctl -d %s -D", tDevInfo->DevicePath );
  613. fd = popen( CMD, "r");
  614. if( fd != NULL ) {
  615. char * line = NULL;
  616. size_t len = 0;
  617. ssize_t rd;
  618. while ((rd = getline(&line, &len, fd)) != -1) {
  619. char *tS1, *tS2;
  620. // Future use strcasestr() or make both stings same case
  621. if( ( tS1 = strstr( line, "Bus info" )) != NULL ) {
  622. tS2 = trim( strstr( tS1, ":" ) + 2 );
  623. sprintf( tDevInfo->FriendlyName, "%s", tS2 );
  624. };
  625. };
  626. fclose( fd );
  627. if( line ) free( line );
  628. };
  629. };
  630. mlist->push_back( tDevInfo );
  631. //printf("%s\n", dir->d_name );
  632. };
  633. //if( strncmp( dir->d_name, "ttyS", 4 ) == 0 ){
  634. // tBuffer = ( char * ) malloc( strlen(dir->d_name)+1 );
  635. // strncpy( tBuffer, dir->d_name, strlen(dir->d_name)+1 );
  636. // mlist->pushBack( tBuffer );
  637. // //printf("%s\n", dir->d_name );
  638. //};
  639. };
  640. };
  641. closedir(d);
  642. } else {
  643. return false;
  644. };
  645. return true;
  646. };
  647. #else
  648. #ifndef IID_PPV_ARGS
  649. extern "C++" {
  650. template<typename T> void** IID_PPV_ARGS_Helper(T** pp)
  651. {
  652. // make sure everyone derives from IUnknown
  653. static_cast<IUnknown*>(*pp);
  654. return reinterpret_cast<void**>(pp);
  655. }
  656. }
  657. #define IID_PPV_ARGS(ppType) __uuidof(**(ppType)), IID_PPV_ARGS_Helper(ppType)
  658. #endif
  659. #pragma comment(lib,"Strmiids.lib")
  660. bool enumerateDevices(enumeratorInfo *mlist, REFGUID category){
  661. HRESULT hr;
  662. bool initOk = true;
  663. hr = CoInitializeEx( NULL, COINIT_SPEED_OVER_MEMORY | COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE );
  664. if( hr == E_INVALIDARG ){
  665. printf("Couldn't Init! hr=0x%x", hr);
  666. return false;
  667. } else if ( hr == E_OUTOFMEMORY ){
  668. printf("Couldn't Init! hr=0x%x", hr);
  669. return false;
  670. } else if ( hr == E_UNEXPECTED ){
  671. printf("Couldn't Init! hr=0x%x", hr);
  672. return false;
  673. } else if( hr == RPC_E_CHANGED_MODE ){
  674. initOk = false;
  675. };
  676. if( hr == S_OK || hr == RPC_E_CHANGED_MODE ){
  677. // Create the system device enumerator
  678. ICreateDevEnum *pDevEnum;
  679. hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum) );
  680. if( hr != S_OK ){
  681. printf("Couldn't create system enumerator! hr=0x%x", hr);
  682. CoUninitialize();
  683. return false;
  684. };
  685. if( pDevEnum != NULL ){
  686. IEnumMoniker *pClsEnum = NULL;
  687. hr = pDevEnum->CreateClassEnumerator(category, &pClsEnum, 0);
  688. if( hr == S_FALSE ){
  689. // The category is empty. Treat as an error.
  690. pDevEnum->Release();
  691. CoUninitialize();
  692. return false;
  693. };
  694. if( pClsEnum != NULL ){
  695. IMoniker *pMoniker = NULL;
  696. while( pClsEnum->Next(1, &pMoniker, NULL) == S_OK ){
  697. IPropertyBag *pPropBag = NULL;
  698. hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
  699. if( FAILED(hr) ){
  700. pMoniker->Release();
  701. continue;
  702. };
  703. VARIANT var;
  704. VariantInit(&var);
  705. DeviceInfo *tRec;
  706. tRec = (DeviceInfo *)malloc(sizeof(DeviceInfo));
  707. // Get description or friendly name.
  708. hr = pPropBag->Read(L"Description", &var, 0);
  709. if( FAILED(hr) ){
  710. hr = pPropBag->Read(L"FriendlyName", &var, 0);
  711. };
  712. if (SUCCEEDED(hr)){
  713. if (tRec != NULL) {
  714. sprintf(tRec->FriendlyName, "%S", var.bstrVal);
  715. mlist->push_back(tRec);
  716. };
  717. VariantClear(&var);
  718. };
  719. hr = pPropBag->Write(L"FriendlyName", &var);
  720. // WaveInID applies only to audio capture devices.
  721. hr = pPropBag->Read(L"WaveInID", &var, 0);
  722. if (SUCCEEDED(hr)){
  723. //printf("WaveIn ID: %d\n", var.lVal);
  724. VariantClear(&var);
  725. };
  726. hr = pPropBag->Read(L"DevicePath", &var, 0);
  727. if (SUCCEEDED(hr)){
  728. // The device path is not intended for display.
  729. if( tRec != NULL) {
  730. sprintf(tRec->DevicePath, "%S", var.bstrVal);
  731. };
  732. VariantClear(&var);
  733. };
  734. pPropBag->Release();
  735. pMoniker->Release();
  736. };
  737. pClsEnum->Release();
  738. };
  739. pDevEnum->Release();
  740. };
  741. if( initOk ) CoUninitialize();
  742. };
  743. return true;
  744. };
  745. #endif
  746. size_t escape_string( char *to, size_t to_length, const char *from, size_t length ){
  747. const char *to_start = to;
  748. const char *end, *to_end = to_start + (to_length ? to_length - 1 : 2 * length);
  749. bool overflow = false;
  750. for( end = from + length; from < end; from++ ) {
  751. char escape = 0;
  752. int tmp_length;
  753. /*
  754. If the next character appears to begin a multi-byte character, we
  755. escape that first byte of that apparent multi-byte character. (The
  756. character just looks like a multi-byte character -- if it were actually
  757. a multi-byte character, it would have been passed through in the test
  758. above.)
  759. Without this check, we can create a problem by converting an invalid
  760. multi-byte character into a valid one. For example, 0xbf27 is not
  761. a valid GBK character, but 0xbf5c is. (0x27 = ', 0x5c = \)
  762. */
  763. tmp_length = 0;
  764. if( tmp_length > 1 ){
  765. escape = *from;
  766. } else{
  767. switch (*from) {
  768. case 0: /* Must be escaped for 'mysql' */
  769. escape = '0';
  770. break;
  771. case '\n': /* Must be escaped for logs */
  772. escape = 'n';
  773. break;
  774. case '\r':
  775. escape = 'r';
  776. break;
  777. case '\\':
  778. escape = '\\';
  779. break;
  780. case '\'':
  781. escape = '\'';
  782. break;
  783. case '"': /* Better safe than sorry */
  784. escape = '"';
  785. break;
  786. case '\032': /* This gives problems on Win32 */
  787. escape = 'Z';
  788. break;
  789. };
  790. };
  791. if( escape ) {
  792. if (to + 2 > to_end) { overflow = true; break; };
  793. *to++ = '\\';
  794. *to++ = escape;
  795. } else {
  796. if (to + 1 > to_end) { overflow = true; break; };
  797. *to++ = *from;
  798. };
  799. };
  800. *to = 0;
  801. return overflow ? (size_t)-1 : (size_t)(to - to_start);
  802. };
  803. /* Read characters from 'fd' until a newline is encountered. If a newline
  804. character is not encountered in the first (n - 1) bytes, then the excess
  805. characters are discarded. The returned string placed in 'buf' is
  806. null-terminated and includes the newline character if it was read in the
  807. first (n - 1) bytes. The function return value is the number of bytes
  808. placed in buffer (which includes the newline character if encountered,
  809. but excludes the terminating null byte). */
  810. ssize_t readLine(int fd, char *buffer, size_t n) {
  811. ssize_t numRead; /* # of bytes fetched by last read() */
  812. size_t totRead; /* Total bytes read so far */
  813. char *buf;
  814. char ch;
  815. if (n <= 0 || buffer == NULL) {
  816. errno = EINVAL;
  817. return -1;
  818. }
  819. buf = buffer; /* No pointer arithmetic on "void *" */
  820. totRead = 0;
  821. for (;;) {
  822. numRead = read(fd, &ch, 1);
  823. if (numRead == -1) {
  824. if (errno == EINTR) /* Interrupted --> restart read() */
  825. continue;
  826. else
  827. return -1; /* Some other error */
  828. } else if (numRead == 0) { /* EOF */
  829. if (totRead == 0) /* No bytes read; return 0 */
  830. return 0;
  831. else /* Some bytes read; add '\0' */
  832. break;
  833. } else { /* 'numRead' must be 1 if we get here */
  834. if (totRead < n - 1) { /* Discard > (n - 1) bytes */
  835. totRead++;
  836. *buf++ = ch;
  837. }
  838. if (ch == '\n')
  839. break;
  840. }
  841. }
  842. *buf = '\0';
  843. return totRead;
  844. };
  845. ssize_t readLine( FILE *fd, char *buffer, size_t n) {
  846. ssize_t numRead; /* # of bytes fetched by last read() */
  847. size_t totRead; /* Total bytes read so far */
  848. char *buf;
  849. char ch;
  850. if (n <= 0 || buffer == NULL) {
  851. errno = EINVAL;
  852. return -1;
  853. }
  854. buf = buffer; /* No pointer arithmetic on "void *" */
  855. totRead = 0;
  856. for (;;) {
  857. numRead = fread(&ch, 1, 1, fd);
  858. if (numRead == -1) {
  859. if (errno == EINTR) /* Interrupted --> restart read() */
  860. continue;
  861. else
  862. return -1; /* Some other error */
  863. } else if (numRead == 0) { /* EOF */
  864. if (totRead == 0) /* No bytes read; return 0 */
  865. return 0;
  866. else /* Some bytes read; add '\0' */
  867. break;
  868. } else { /* 'numRead' must be 1 if we get here */
  869. if (totRead < n - 1) { /* Discard > (n - 1) bytes */
  870. totRead++;
  871. *buf++ = ch;
  872. }
  873. if (ch == '\n')
  874. break;
  875. }
  876. }
  877. *buf = '\0';
  878. return totRead;
  879. };
  880. localIpAddresses g_vLocalIpAdressess;
  881. bool g_bAdressesAreDiscovered = false;
  882. #ifdef __linux__
  883. bool isProcessUniq( CSTR pName ){
  884. char tB[256];
  885. FILE *fd;
  886. sprintf( tB, "pidof %s", pName );
  887. fd = popen( tB, "r" );
  888. if ( fd ) {
  889. int rs = readLine( fd, tB, 256 );
  890. if ( rs > 2 ) {
  891. fclose( fd );
  892. return false;
  893. };
  894. fclose( fd );
  895. };
  896. return true;
  897. };
  898. #include <linux/if.h>
  899. localIpAddresses *getLocalIP(){
  900. // Check for Filter LO and TUN Devices!
  901. if( !g_bAdressesAreDiscovered ) {
  902. struct ifaddrs *ifaddr, *ifa;
  903. localIp4Info *tIpAddress = NULL;
  904. if (getifaddrs(&ifaddr) != -1) {
  905. /* Walk through linked list, maintaining head pointer so we can free list later */
  906. for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
  907. // Filter Loopback if
  908. if( strstr( ifa->ifa_name, "lo" ) != NULL ) continue;
  909. // Filter vpn TUN if
  910. if( strstr( ifa->ifa_name, "tun" ) != NULL ) continue;
  911. char protocol[IFNAMSIZ] = {0};
  912. if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET) continue;
  913. tIpAddress = (localIp4Info*)malloc(sizeof(localIp4Info));
  914. if(tIpAddress!=NULL){
  915. sprintf( tIpAddress->address , "%d.%d.%d.%d",
  916. (uint8_t)ifa->ifa_addr->sa_data[2],
  917. (uint8_t)ifa->ifa_addr->sa_data[3],
  918. (uint8_t)ifa->ifa_addr->sa_data[4],
  919. (uint8_t)ifa->ifa_addr->sa_data[5]
  920. );
  921. sprintf( tIpAddress->netmask , "%d.%d.%d.%d",
  922. (uint8_t)ifa->ifa_netmask->sa_data[2],
  923. (uint8_t)ifa->ifa_netmask->sa_data[3],
  924. (uint8_t)ifa->ifa_netmask->sa_data[4],
  925. (uint8_t)ifa->ifa_netmask->sa_data[5]
  926. );
  927. sprintf( tIpAddress->broadcast , "%d.%d.%d.%d",
  928. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2],
  929. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3],
  930. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4],
  931. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5]
  932. );
  933. g_vLocalIpAdressess.push_back(tIpAddress);
  934. };
  935. };
  936. freeifaddrs(ifaddr);
  937. };
  938. g_bAdressesAreDiscovered = true;
  939. };
  940. return &g_vLocalIpAdressess;
  941. };
  942. #else // !linux
  943. //https://stackoverflow.com/questions/5213629/how-to-enumerate-all-available-network-interfaces
  944. #include <iphlpapi.h>
  945. #pragma comment(lib, "IPHLPAPI.lib")
  946. localIpAddresses* getLocalIP() {
  947. char psBuffer[128];
  948. FILE* fd;
  949. BYTE mB;
  950. localIp4Info* tIpAddress;
  951. if (!g_bAdressesAreDiscovered) {
  952. ULONG outBufLen = 0;
  953. DWORD dwRetVal = 0;
  954. IP_ADAPTER_INFO* pAdapterInfos = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
  955. // retry up to 5 times, to get the adapter infos needed
  956. for (int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i) {
  957. dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen);
  958. if (dwRetVal == NO_ERROR) {
  959. break;
  960. } else {
  961. if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
  962. free(pAdapterInfos);
  963. pAdapterInfos = (IP_ADAPTER_INFO*)malloc(outBufLen);
  964. } else {
  965. //pAdapterInfos = 0;
  966. break;
  967. };
  968. };
  969. };
  970. if (dwRetVal == NO_ERROR) {
  971. IP_ADAPTER_INFO* pAdapterInfo = pAdapterInfos;
  972. while (pAdapterInfo) {
  973. IP_ADDR_STRING* pIpAddress = &(pAdapterInfo->IpAddressList);
  974. while (pIpAddress != 0) {
  975. uint8_t A, B, C, D;
  976. uint8_t M, O, S, K, G, U, T, E;
  977. uint32_t Z1, Z2, Z3, Z4;
  978. int RetVal;
  979. RetVal = sscanf(pIpAddress->IpAddress.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  980. A = Z1 & 0xFF;
  981. B = Z2 & 0xFF;
  982. C = Z3 & 0xFF;
  983. D = Z4 & 0xFF;
  984. RetVal = sscanf(pIpAddress->IpMask.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  985. M = Z1 & 0xFF;
  986. O = Z2 & 0xFF;
  987. S = Z3 & 0xFF;
  988. K = Z4 & 0xFF;
  989. //
  990. // <<<<
  991. // here pAdapterInfo->Address should contain the MAC address
  992. // >>>>
  993. //
  994. if (A > 0) {
  995. tIpAddress = (localIp4Info*)malloc(sizeof(localIp4Info));
  996. if (tIpAddress != NULL) {
  997. sprintf(tIpAddress->address, "%d.%d.%d.%d", A, B, C, D );
  998. sprintf(tIpAddress->netmask, "%d.%d.%d.%d", M, O, S, K );
  999. G = (A & M) | (~M);
  1000. U = (B & O) | (~O);
  1001. T = (C & S) | (~S);
  1002. E = (D & K) | (~K);
  1003. sprintf(tIpAddress->broadcast, "%d.%d.%d.%d", G, U, T, E );
  1004. g_vLocalIpAdressess.push_back(tIpAddress);
  1005. };
  1006. };
  1007. pIpAddress = pIpAddress->Next;
  1008. };
  1009. pAdapterInfo = pAdapterInfo->Next;
  1010. };
  1011. };
  1012. free(pAdapterInfos);
  1013. };
  1014. return &g_vLocalIpAdressess;
  1015. };
  1016. #endif
  1017. #ifdef DEBUG
  1018. #undef URGENT_LOG
  1019. #endif