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.

1111 lines
31 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. void getUniqID_UUID( CSTR buf, uint32_t SEED ){
  286. CSTR tVal = NULL;
  287. CSTR tMD5 = NULL;
  288. tVal = getTimeStamp();
  289. buf[0] = (char)0;
  290. if( tVal ){
  291. char tt[256];
  292. sprintf( tt, "%s %d %d", tVal ,SEED, UID_INCREMEMTAL );
  293. tMD5 = MD5String( tt );
  294. if( tMD5 ) {
  295. memcpy( buf, tMD5, 8 );
  296. buf[8] = '-';
  297. memcpy( buf+9, tMD5+8, 4 );
  298. buf[13] = '-';
  299. memcpy( buf+14, tMD5+12, 4 );
  300. buf[18] = '-';
  301. memcpy( buf+19, tMD5+16, 4 );
  302. buf[23] = '-';
  303. memcpy( buf+24, tMD5+20, 12 );
  304. buf[36] = (char)0;
  305. free( tMD5 );
  306. };
  307. free( tVal );
  308. };
  309. };
  310. CSTR getUniqID_UUID( uint32_t SEED ){
  311. char buf[37];
  312. getUniqID_UUID( buf, SEED );
  313. #ifdef __linux__
  314. return strdup( buf );
  315. #else
  316. return _strdup( buf );
  317. #endif
  318. };
  319. CSTR trim( CSTR val ){
  320. int i = 0;
  321. int j = strlen( val );
  322. if( j ){
  323. while(( i < j ) && (((unsigned char)val[i])< 0x21 )) i++;
  324. while(( j > i ) && (((unsigned char)val[j])< 0x21 )) j--;
  325. if( ( i > 0 ) && ((j-i+1) > 0 ) ) memcpy( val, val+i, j-i+1 );
  326. val[j-i+1]=(char)0;
  327. };
  328. return val;
  329. };
  330. // orig - input String to Search In
  331. // rep - token to search
  332. // with - replacement for token
  333. // in case with is NULL - cutting off the token
  334. // You must free the result if result is non-NULL.
  335. CSTR strReplace( CSTR orig, CSTR rep, CSTR with ){
  336. char *result; // the return string
  337. char *ins; // the next insert point
  338. char *tmp; // varies
  339. int len_rep; // length of rep (the string to remove)
  340. int len_with; // length of with (the string to replace rep with)
  341. int len_front; // distance between rep and end of last rep
  342. int count; // number of replacements
  343. // sanity checks and initialization
  344. if (!orig || !rep) return NULL;
  345. len_rep = strlen(rep);
  346. if (len_rep == 0) return NULL; // empty rep causes infinite loop during count
  347. if (!with) with =(CSTR)""; // In case With not suplied - just cut off Token
  348. len_with = strlen(with);
  349. // count the number of replacements needed
  350. ins = orig;
  351. for (count = 0; tmp = strstr(ins, rep); ++count) {
  352. ins = tmp + len_rep;
  353. }
  354. tmp = result = (CSTR) malloc(strlen(orig) + (len_with - len_rep) * count + 1);
  355. if( !result ) return NULL;
  356. // first time through the loop, all the variable are set correctly
  357. // from here on,
  358. // tmp points to the end of the result string
  359. // ins points to the next occurrence of rep in orig
  360. // orig points to the remainder of orig after "end of rep"
  361. while (count--) {
  362. ins = strstr(orig, rep);
  363. len_front = ins - orig;
  364. tmp = strncpy(tmp, orig, len_front) + len_front;
  365. tmp = strcpy(tmp, with) + len_with;
  366. orig += len_front + len_rep; // move to next "end of rep"
  367. }
  368. strcpy(tmp, orig);
  369. return result;
  370. };
  371. uint8_t checksum8( uint8_t *Buffer, size_t BufferSize ){
  372. uint16_t TempVal;
  373. TempVal = 0;
  374. for( int index = 0; index < BufferSize; index++ ) {
  375. TempVal+=Buffer[index];
  376. };
  377. return (uint8_t)(TempVal & 0x00FF);
  378. };
  379. uint16_t checksum16( uint8_t *Buffer, size_t BufferSize ){
  380. uint32_t TempVal;
  381. TempVal = 0;
  382. for( int index = 0; index < BufferSize; index++ ) {
  383. TempVal+=Buffer[index];
  384. };
  385. return (uint16_t)(TempVal & 0x0000FFFF);
  386. };
  387. uint8_t checksumLGS( uint8_t *Buffer, size_t BufferSize ){
  388. uint16_t TempVal;
  389. TempVal = 0;
  390. for( int index = 0; index < BufferSize; index++ ) {
  391. TempVal+=Buffer[index];
  392. };
  393. return (uint8_t)(TempVal & 0x00FF);
  394. };
  395. // Calculating the Check Sum for Ping package
  396. uint16_t checksumPing(void *b, size_t len){
  397. uint16_t *buf = (uint16_t *) b;
  398. uint32_t sum=0;
  399. uint16_t result;
  400. for ( sum = 0; len > 1; len -= 2 )
  401. sum += *buf++;
  402. if ( len == 1 )
  403. sum += *(unsigned char*)buf;
  404. sum = (sum >> 16) + (sum & 0xFFFF);
  405. sum += (sum >> 16);
  406. result = ~sum;
  407. return result;
  408. };
  409. CArray *explode( char Delim, CSTR S_Str ){
  410. bool ws = false;
  411. CArray * RetVal = NULL;
  412. CSTR b_ptr = S_Str;
  413. U16 s_ptr = 0;
  414. if( S_Str ){
  415. RetVal = new CArray;
  416. if( RetVal ){
  417. while ((U8)S_Str[s_ptr]) {
  418. if( (( U8 ) Delim ) == (( U8 )S_Str[s_ptr]) ){
  419. if (!ws) {
  420. ws = true;
  421. S_Str[s_ptr] = (char)0;
  422. RetVal->push_back( b_ptr );
  423. s_ptr++;
  424. b_ptr = &S_Str[s_ptr];
  425. } else s_ptr++;
  426. } else {
  427. ws = false;
  428. s_ptr++;
  429. };
  430. };
  431. RetVal->push_back( b_ptr );
  432. };
  433. };
  434. return RetVal;
  435. };
  436. CSTR implode( CArray *Data, CSTR S_Str, U8 Start, U8 End ){
  437. CSTR RetVal;
  438. U8 RStart = Start;
  439. U8 REnd = End;
  440. if( Start > Data->size() ) return NULL;
  441. if( End < Start ) return NULL;
  442. if( End > Data->size() ) REnd = (U8)(Data->size()-1);
  443. if( strlen( (*Data).at( RStart )) ){
  444. RetVal = (CSTR) malloc( strlen( (*Data).at( RStart )) + 1 );
  445. sprintf( RetVal,"%s",(*Data).at( RStart ));
  446. } else {
  447. RetVal = (CSTR) malloc( 1 );
  448. *RetVal=(char)0;
  449. };
  450. if (RetVal != NULL) {
  451. for (int i = RStart + 1; i < REnd; i++) {
  452. RetVal = (CSTR)realloc(RetVal, strlen(RetVal) + strlen((*Data).at(i)) + 1 + strlen(S_Str));
  453. sprintf(RetVal, "%s%s%s", RetVal, S_Str, (*Data).at(i));
  454. };
  455. };
  456. return RetVal;
  457. };
  458. int getIP4( if_info **arrParam, int max_ifs ){
  459. int index = 0;
  460. #ifdef __linux__
  461. struct ifaddrs *addrs, *tmp;
  462. getifaddrs(&addrs);
  463. tmp = addrs;
  464. //arrParam= malloc( 10 * sezeof(if_info) );
  465. while (tmp){
  466. if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_INET){
  467. if( strncmp( tmp->ifa_name, "lo", 2 ) != 0 ){
  468. (*arrParam)[index].if_name = (CSTR)malloc(strlen(tmp->ifa_name)+1);
  469. snprintf( (*arrParam)[index].if_name, strlen(tmp->ifa_name)+1,"%s", tmp->ifa_name );
  470. (*arrParam)[index].if_addr = (CSTR)malloc(16);
  471. struct sockaddr_in *pAddr = (struct sockaddr_in *)tmp->ifa_addr;
  472. snprintf( (*arrParam)[index].if_addr, 16, "%s", inet_ntoa(pAddr->sin_addr) );
  473. index++;
  474. if( index == max_ifs ) break;
  475. }
  476. };
  477. tmp = tmp->ifa_next;
  478. };
  479. freeifaddrs(addrs);
  480. #endif
  481. return index;
  482. };
  483. #ifdef __linux__
  484. long long getFreeSpace( CSTR DirName ){
  485. struct statvfs fiData;
  486. if( ( statvfs( DirName, &fiData ) ) < 0 ) {
  487. return -1;
  488. };
  489. return fiData.f_bsize * fiData.f_bfree;
  490. };
  491. long long getTotalSpace( CSTR DirName ){
  492. struct statvfs fiData;
  493. if( ( statvfs( DirName, &fiData ) ) < 0 ) {
  494. return -1;
  495. };
  496. return fiData.f_bsize * fiData.f_blocks;
  497. };
  498. #else
  499. __int64 getFreeSpace( CSTR DirName ){
  500. return -1;
  501. };
  502. __int64 getTotalSpace( CSTR DirName ){
  503. return -1;
  504. };
  505. #endif
  506. CSTR getTStr( CSTR Fmt ){
  507. //CSTR RetVal = NULL;
  508. char DateStr[200];
  509. time_t t;
  510. struct tm *tmp;
  511. t = time(NULL);
  512. tmp = gmtime(&t);
  513. if( tmp == NULL) {
  514. fprintf(stderr, "localtime!");
  515. return NULL;
  516. };
  517. if( Fmt == NULL ) {
  518. if( strftime( DateStr, 200, "%F %T GMT", tmp )==0 ){
  519. fprintf( stderr, "strftime returned 0" );
  520. return NULL;
  521. };
  522. } else {
  523. if( strftime( DateStr, 200, Fmt, tmp )==0 ){
  524. fprintf( stderr, "strftime returned 0" );
  525. return NULL;
  526. };
  527. }
  528. //RetVal =(CSTR) malloc( strlen(DateStr) +1 );
  529. //if( RetVal != NULL ) strcpy( RetVal, DateStr );
  530. #ifdef __linux__
  531. return strdup(DateStr);
  532. #else
  533. return _strdup(DateStr);
  534. #endif
  535. };
  536. #ifdef __linux__
  537. int xioctl(int fh, int request, void *arg){
  538. int r;
  539. do {
  540. r = ioctl( fh, request, arg );
  541. } while (-1 == r && EINTR == errno);
  542. return r;
  543. };
  544. uint64_t getMilliseconds( void ){
  545. uint64_t tMilliseconds = (uint64_t) 0;
  546. struct timeval tData;
  547. struct timezone tTZ;
  548. tTZ.tz_minuteswest = 0;
  549. tTZ.tz_dsttime = 0;
  550. if( gettimeofday( &tData, &tTZ ) == -1 ){
  551. tMilliseconds = (uint64_t) 0;
  552. #ifdef DEBUG
  553. URGENT_LOG( "EbioMat'!");
  554. #endif
  555. } else {
  556. tMilliseconds = (uint64_t) tData.tv_sec;
  557. tMilliseconds = ( tMilliseconds * 1000 );
  558. tMilliseconds += (uint64_t)( tData.tv_usec / 1000 );
  559. //URGENT_LOG("MilSecCollected!");
  560. };
  561. #else
  562. #include<ctime>
  563. unsigned __int64 getMilliseconds( void ){
  564. unsigned __int64 tMilliseconds;
  565. SYSTEMTIME time;
  566. GetSystemTime(&time);
  567. tMilliseconds = (uint32_t)std::time(NULL);
  568. tMilliseconds *= 1000;
  569. tMilliseconds += time.wMilliseconds;
  570. #endif
  571. return tMilliseconds;
  572. };
  573. #ifdef __linux__
  574. bool enumerateDevices( enumeratorInfo *mlist, const char *dTemplate){
  575. DIR *d;
  576. struct dirent *dir;
  577. DeviceInfo *tDevInfo;
  578. if( mlist == NULL )return false;
  579. if( dTemplate == NULL )return false;
  580. for( int i = 0; i < mlist->size(); i++ ) {
  581. delete( mlist->at(i) );
  582. };
  583. mlist->clear();
  584. d = opendir("/dev");
  585. if( d ){
  586. while((dir = readdir(d)) != NULL){
  587. if( dir->d_type == DT_CHR || dir->d_type == DT_BLK ){
  588. if( strncmp( dir->d_name, dTemplate, 5 ) == 0 ) {
  589. tDevInfo = (DeviceInfo *) malloc( sizeof(DeviceInfo) );
  590. sprintf( tDevInfo->DevicePath, "/dev/%s", dir->d_name );
  591. tDevInfo->FriendlyName[0] =(char)0;
  592. if( strncmp( dTemplate, "video", 5 ) == 0 ){
  593. FILE *fd;
  594. char CMD[256];
  595. sprintf( CMD, "v4l2-ctl -d %s -D", tDevInfo->DevicePath );
  596. fd = popen( CMD, "r");
  597. if( fd != NULL ) {
  598. char * line = NULL;
  599. size_t len = 0;
  600. ssize_t rd;
  601. while ((rd = getline(&line, &len, fd)) != -1) {
  602. char *tS1, *tS2;
  603. // Future use strcasestr() or make both stings same case
  604. if( ( tS1 = strstr( line, "Bus info" )) != NULL ) {
  605. tS2 = trim( strstr( tS1, ":" ) + 2 );
  606. sprintf( tDevInfo->FriendlyName, "%s", tS2 );
  607. };
  608. };
  609. fclose( fd );
  610. if( line ) free( line );
  611. };
  612. };
  613. mlist->push_back( tDevInfo );
  614. //printf("%s\n", dir->d_name );
  615. };
  616. //if( strncmp( dir->d_name, "ttyS", 4 ) == 0 ){
  617. // tBuffer = ( char * ) malloc( strlen(dir->d_name)+1 );
  618. // strncpy( tBuffer, dir->d_name, strlen(dir->d_name)+1 );
  619. // mlist->pushBack( tBuffer );
  620. // //printf("%s\n", dir->d_name );
  621. //};
  622. };
  623. };
  624. closedir(d);
  625. } else {
  626. return false;
  627. };
  628. return true;
  629. };
  630. #else
  631. #ifndef IID_PPV_ARGS
  632. extern "C++" {
  633. template<typename T> void** IID_PPV_ARGS_Helper(T** pp)
  634. {
  635. // make sure everyone derives from IUnknown
  636. static_cast<IUnknown*>(*pp);
  637. return reinterpret_cast<void**>(pp);
  638. }
  639. }
  640. #define IID_PPV_ARGS(ppType) __uuidof(**(ppType)), IID_PPV_ARGS_Helper(ppType)
  641. #endif
  642. #pragma comment(lib,"Strmiids.lib")
  643. bool enumerateDevices(enumeratorInfo *mlist, REFGUID category){
  644. HRESULT hr;
  645. bool initOk = true;
  646. hr = CoInitializeEx( NULL, COINIT_SPEED_OVER_MEMORY | COINIT_MULTITHREADED | COINIT_DISABLE_OLE1DDE );
  647. if( hr == E_INVALIDARG ){
  648. printf("Couldn't Init! hr=0x%x", hr);
  649. return false;
  650. } else if ( hr == E_OUTOFMEMORY ){
  651. printf("Couldn't Init! hr=0x%x", hr);
  652. return false;
  653. } else if ( hr == E_UNEXPECTED ){
  654. printf("Couldn't Init! hr=0x%x", hr);
  655. return false;
  656. } else if( hr == RPC_E_CHANGED_MODE ){
  657. initOk = false;
  658. };
  659. if( hr == S_OK || hr == RPC_E_CHANGED_MODE ){
  660. // Create the system device enumerator
  661. ICreateDevEnum *pDevEnum;
  662. hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pDevEnum) );
  663. if( hr != S_OK ){
  664. printf("Couldn't create system enumerator! hr=0x%x", hr);
  665. CoUninitialize();
  666. return false;
  667. };
  668. if( pDevEnum != NULL ){
  669. IEnumMoniker *pClsEnum = NULL;
  670. hr = pDevEnum->CreateClassEnumerator(category, &pClsEnum, 0);
  671. if( hr == S_FALSE ){
  672. // The category is empty. Treat as an error.
  673. pDevEnum->Release();
  674. CoUninitialize();
  675. return false;
  676. };
  677. if( pClsEnum != NULL ){
  678. IMoniker *pMoniker = NULL;
  679. while( pClsEnum->Next(1, &pMoniker, NULL) == S_OK ){
  680. IPropertyBag *pPropBag = NULL;
  681. hr = pMoniker->BindToStorage(0, 0, IID_PPV_ARGS(&pPropBag));
  682. if( FAILED(hr) ){
  683. pMoniker->Release();
  684. continue;
  685. };
  686. VARIANT var;
  687. VariantInit(&var);
  688. DeviceInfo *tRec;
  689. tRec = (DeviceInfo *)malloc(sizeof(DeviceInfo));
  690. // Get description or friendly name.
  691. hr = pPropBag->Read(L"Description", &var, 0);
  692. if( FAILED(hr) ){
  693. hr = pPropBag->Read(L"FriendlyName", &var, 0);
  694. };
  695. if (SUCCEEDED(hr)){
  696. if (tRec != NULL) {
  697. sprintf(tRec->FriendlyName, "%S", var.bstrVal);
  698. mlist->push_back(tRec);
  699. };
  700. VariantClear(&var);
  701. };
  702. hr = pPropBag->Write(L"FriendlyName", &var);
  703. // WaveInID applies only to audio capture devices.
  704. hr = pPropBag->Read(L"WaveInID", &var, 0);
  705. if (SUCCEEDED(hr)){
  706. //printf("WaveIn ID: %d\n", var.lVal);
  707. VariantClear(&var);
  708. };
  709. hr = pPropBag->Read(L"DevicePath", &var, 0);
  710. if (SUCCEEDED(hr)){
  711. // The device path is not intended for display.
  712. if( tRec != NULL) {
  713. sprintf(tRec->DevicePath, "%S", var.bstrVal);
  714. };
  715. VariantClear(&var);
  716. };
  717. pPropBag->Release();
  718. pMoniker->Release();
  719. };
  720. pClsEnum->Release();
  721. };
  722. pDevEnum->Release();
  723. };
  724. if( initOk ) CoUninitialize();
  725. };
  726. return true;
  727. };
  728. #endif
  729. size_t escape_string( char *to, size_t to_length, const char *from, size_t length ){
  730. const char *to_start = to;
  731. const char *end, *to_end = to_start + (to_length ? to_length - 1 : 2 * length);
  732. bool overflow = false;
  733. for( end = from + length; from < end; from++ ) {
  734. char escape = 0;
  735. int tmp_length;
  736. /*
  737. If the next character appears to begin a multi-byte character, we
  738. escape that first byte of that apparent multi-byte character. (The
  739. character just looks like a multi-byte character -- if it were actually
  740. a multi-byte character, it would have been passed through in the test
  741. above.)
  742. Without this check, we can create a problem by converting an invalid
  743. multi-byte character into a valid one. For example, 0xbf27 is not
  744. a valid GBK character, but 0xbf5c is. (0x27 = ', 0x5c = \)
  745. */
  746. tmp_length = 0;
  747. if( tmp_length > 1 ){
  748. escape = *from;
  749. } else{
  750. switch (*from) {
  751. case 0: /* Must be escaped for 'mysql' */
  752. escape = '0';
  753. break;
  754. case '\n': /* Must be escaped for logs */
  755. escape = 'n';
  756. break;
  757. case '\r':
  758. escape = 'r';
  759. break;
  760. case '\\':
  761. escape = '\\';
  762. break;
  763. case '\'':
  764. escape = '\'';
  765. break;
  766. case '"': /* Better safe than sorry */
  767. escape = '"';
  768. break;
  769. case '\032': /* This gives problems on Win32 */
  770. escape = 'Z';
  771. break;
  772. };
  773. };
  774. if( escape ) {
  775. if (to + 2 > to_end) { overflow = true; break; };
  776. *to++ = '\\';
  777. *to++ = escape;
  778. } else {
  779. if (to + 1 > to_end) { overflow = true; break; };
  780. *to++ = *from;
  781. };
  782. };
  783. *to = 0;
  784. return overflow ? (size_t)-1 : (size_t)(to - to_start);
  785. };
  786. /* Read characters from 'fd' until a newline is encountered. If a newline
  787. character is not encountered in the first (n - 1) bytes, then the excess
  788. characters are discarded. The returned string placed in 'buf' is
  789. null-terminated and includes the newline character if it was read in the
  790. first (n - 1) bytes. The function return value is the number of bytes
  791. placed in buffer (which includes the newline character if encountered,
  792. but excludes the terminating null byte). */
  793. ssize_t readLine(int fd, char *buffer, size_t n) {
  794. ssize_t numRead; /* # of bytes fetched by last read() */
  795. size_t totRead; /* Total bytes read so far */
  796. char *buf;
  797. char ch;
  798. if (n <= 0 || buffer == NULL) {
  799. errno = EINVAL;
  800. return -1;
  801. }
  802. buf = buffer; /* No pointer arithmetic on "void *" */
  803. totRead = 0;
  804. for (;;) {
  805. numRead = read(fd, &ch, 1);
  806. if (numRead == -1) {
  807. if (errno == EINTR) /* Interrupted --> restart read() */
  808. continue;
  809. else
  810. return -1; /* Some other error */
  811. } else if (numRead == 0) { /* EOF */
  812. if (totRead == 0) /* No bytes read; return 0 */
  813. return 0;
  814. else /* Some bytes read; add '\0' */
  815. break;
  816. } else { /* 'numRead' must be 1 if we get here */
  817. if (totRead < n - 1) { /* Discard > (n - 1) bytes */
  818. totRead++;
  819. *buf++ = ch;
  820. }
  821. if (ch == '\n')
  822. break;
  823. }
  824. }
  825. *buf = '\0';
  826. return totRead;
  827. };
  828. ssize_t readLine( FILE *fd, char *buffer, size_t n) {
  829. ssize_t numRead; /* # of bytes fetched by last read() */
  830. size_t totRead; /* Total bytes read so far */
  831. char *buf;
  832. char ch;
  833. if (n <= 0 || buffer == NULL) {
  834. errno = EINVAL;
  835. return -1;
  836. }
  837. buf = buffer; /* No pointer arithmetic on "void *" */
  838. totRead = 0;
  839. for (;;) {
  840. numRead = fread(&ch, 1, 1, fd);
  841. if (numRead == -1) {
  842. if (errno == EINTR) /* Interrupted --> restart read() */
  843. continue;
  844. else
  845. return -1; /* Some other error */
  846. } else if (numRead == 0) { /* EOF */
  847. if (totRead == 0) /* No bytes read; return 0 */
  848. return 0;
  849. else /* Some bytes read; add '\0' */
  850. break;
  851. } else { /* 'numRead' must be 1 if we get here */
  852. if (totRead < n - 1) { /* Discard > (n - 1) bytes */
  853. totRead++;
  854. *buf++ = ch;
  855. }
  856. if (ch == '\n')
  857. break;
  858. }
  859. }
  860. *buf = '\0';
  861. return totRead;
  862. };
  863. localIpAddresses g_vLocalIpAdressess;
  864. bool g_bAdressesAreDiscovered = false;
  865. #ifdef __linux__
  866. bool isProcessUniq( CSTR pName ){
  867. char tB[256];
  868. FILE *fd;
  869. sprintf( tB, "pidof %s", pName );
  870. fd = popen( tB, "r" );
  871. if ( fd ) {
  872. int rs = readLine( fd, tB, 256 );
  873. if ( rs > 2 ) {
  874. fclose( fd );
  875. return false;
  876. };
  877. fclose( fd );
  878. };
  879. return true;
  880. };
  881. #include <linux/if.h>
  882. localIpAddresses *getLocalIP(){
  883. // Check for Filter LO and TUN Devices!
  884. if( !g_bAdressesAreDiscovered ) {
  885. struct ifaddrs *ifaddr, *ifa;
  886. localIp4Info *tIpAddress = NULL;
  887. if (getifaddrs(&ifaddr) != -1) {
  888. /* Walk through linked list, maintaining head pointer so we can free list later */
  889. for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
  890. // Filter Loopback if
  891. if( strstr( ifa->ifa_name, "lo" ) != NULL ) continue;
  892. // Filter vpn TUN if
  893. if( strstr( ifa->ifa_name, "tun" ) != NULL ) continue;
  894. char protocol[IFNAMSIZ] = {0};
  895. if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET) continue;
  896. tIpAddress = (localIp4Info*)malloc(sizeof(localIp4Info));
  897. if(tIpAddress!=NULL){
  898. sprintf( tIpAddress->address , "%d.%d.%d.%d",
  899. (uint8_t)ifa->ifa_addr->sa_data[2],
  900. (uint8_t)ifa->ifa_addr->sa_data[3],
  901. (uint8_t)ifa->ifa_addr->sa_data[4],
  902. (uint8_t)ifa->ifa_addr->sa_data[5]
  903. );
  904. sprintf( tIpAddress->netmask , "%d.%d.%d.%d",
  905. (uint8_t)ifa->ifa_netmask->sa_data[2],
  906. (uint8_t)ifa->ifa_netmask->sa_data[3],
  907. (uint8_t)ifa->ifa_netmask->sa_data[4],
  908. (uint8_t)ifa->ifa_netmask->sa_data[5]
  909. );
  910. sprintf( tIpAddress->broadcast , "%d.%d.%d.%d",
  911. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[2],
  912. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[3],
  913. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[4],
  914. (uint8_t)ifa->ifa_ifu.ifu_broadaddr->sa_data[5]
  915. );
  916. g_vLocalIpAdressess.push_back(tIpAddress);
  917. };
  918. };
  919. freeifaddrs(ifaddr);
  920. };
  921. g_bAdressesAreDiscovered = true;
  922. };
  923. return &g_vLocalIpAdressess;
  924. };
  925. #else // !linux
  926. //https://stackoverflow.com/questions/5213629/how-to-enumerate-all-available-network-interfaces
  927. #include <iphlpapi.h>
  928. #pragma comment(lib, "IPHLPAPI.lib")
  929. localIpAddresses* getLocalIP() {
  930. char psBuffer[128];
  931. FILE* fd;
  932. BYTE mB;
  933. localIp4Info* tIpAddress;
  934. if (!g_bAdressesAreDiscovered) {
  935. ULONG outBufLen = 0;
  936. DWORD dwRetVal = 0;
  937. IP_ADAPTER_INFO* pAdapterInfos = (IP_ADAPTER_INFO*)malloc(sizeof(IP_ADAPTER_INFO));
  938. // retry up to 5 times, to get the adapter infos needed
  939. for (int i = 0; i < 5 && (dwRetVal == ERROR_BUFFER_OVERFLOW || dwRetVal == NO_ERROR); ++i) {
  940. dwRetVal = GetAdaptersInfo(pAdapterInfos, &outBufLen);
  941. if (dwRetVal == NO_ERROR) {
  942. break;
  943. } else {
  944. if (dwRetVal == ERROR_BUFFER_OVERFLOW) {
  945. free(pAdapterInfos);
  946. pAdapterInfos = (IP_ADAPTER_INFO*)malloc(outBufLen);
  947. } else {
  948. //pAdapterInfos = 0;
  949. break;
  950. };
  951. };
  952. };
  953. if (dwRetVal == NO_ERROR) {
  954. IP_ADAPTER_INFO* pAdapterInfo = pAdapterInfos;
  955. while (pAdapterInfo) {
  956. IP_ADDR_STRING* pIpAddress = &(pAdapterInfo->IpAddressList);
  957. while (pIpAddress != 0) {
  958. uint8_t A, B, C, D;
  959. uint8_t M, O, S, K, G, U, T, E;
  960. uint32_t Z1, Z2, Z3, Z4;
  961. int RetVal;
  962. RetVal = sscanf(pIpAddress->IpAddress.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  963. A = Z1 & 0xFF;
  964. B = Z2 & 0xFF;
  965. C = Z3 & 0xFF;
  966. D = Z4 & 0xFF;
  967. RetVal = sscanf(pIpAddress->IpMask.String, "%d.%d.%d.%d", &Z1, &Z2, &Z3, &Z4);
  968. M = Z1 & 0xFF;
  969. O = Z2 & 0xFF;
  970. S = Z3 & 0xFF;
  971. K = Z4 & 0xFF;
  972. //
  973. // <<<<
  974. // here pAdapterInfo->Address should contain the MAC address
  975. // >>>>
  976. //
  977. if (A > 0) {
  978. tIpAddress = (localIp4Info*)malloc(sizeof(localIp4Info));
  979. if (tIpAddress != NULL) {
  980. sprintf(tIpAddress->address, "%d.%d.%d.%d", A, B, C, D );
  981. sprintf(tIpAddress->netmask, "%d.%d.%d.%d", M, O, S, K );
  982. G = (A & M) | (~M);
  983. U = (B & O) | (~O);
  984. T = (C & S) | (~S);
  985. E = (D & K) | (~K);
  986. sprintf(tIpAddress->broadcast, "%d.%d.%d.%d", G, U, T, E );
  987. g_vLocalIpAdressess.push_back(tIpAddress);
  988. };
  989. };
  990. pIpAddress = pIpAddress->Next;
  991. };
  992. pAdapterInfo = pAdapterInfo->Next;
  993. };
  994. };
  995. free(pAdapterInfos);
  996. };
  997. return &g_vLocalIpAdressess;
  998. };
  999. #endif
  1000. #ifdef DEBUG
  1001. #undef URGENT_LOG
  1002. #endif