utils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. #include "utils.h"
  2. #include <algorithm> // transform
  3. #include <fstream>
  4. #include <sstream>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <string>
  9. #include <time.h>
  10. // http://c-faq.com/lib/randrange.html
  11. int randint(int N) { return rand() / (RAND_MAX / N + 1); }
  12. // http://c-faq.com/lib/randrange.html
  13. // numbers in the range [M, N] could be generated with something like
  14. int randrange(int M, int N) {
  15. return M + rand() / (RAND_MAX / (N - M + 1) + 1);
  16. }
  17. /**
  18. * random_activate()
  19. *
  20. * Is a weight (1-10),
  21. * tests if random number is < weight * 10.
  22. *
  23. * So random_activate(9) happens more frequently
  24. * then random_activate(8) or lower.
  25. *
  26. * This probably needs to be fixed.
  27. * We need a better randint(RANGE) code.
  28. */
  29. int random_activate(int w) {
  30. int r = randint(100);
  31. if (r <= w) {
  32. return 1;
  33. };
  34. return 0;
  35. }
  36. /**
  37. * Display a repr of the given string.
  38. *
  39. * This converts most \n\r\v\f\t codes,
  40. * defaults to \xHH (hex value).
  41. */
  42. char *repr(const char *data) {
  43. static char buffer[40960];
  44. char *cp;
  45. strcpy(buffer, data);
  46. cp = buffer;
  47. while (*cp != 0) {
  48. char c = *cp;
  49. if (c == ' ') {
  50. cp++;
  51. continue;
  52. };
  53. /* Ok, it's form-feed ('\f'), newline ('\n'), carriage return ('\r'),
  54. * horizontal tab ('\t'), and vertical tab ('\v') */
  55. if (strchr("\f\n\r\t\v\?", c) != NULL) {
  56. memmove(cp + 1, cp, strlen(cp) + 1);
  57. *cp = '\\';
  58. cp++;
  59. switch (c) {
  60. case '\f':
  61. *cp = 'f';
  62. cp++;
  63. break;
  64. case '\n':
  65. *cp = 'n';
  66. cp++;
  67. break;
  68. case '\r':
  69. *cp = 'r';
  70. cp++;
  71. break;
  72. case '\t':
  73. *cp = 't';
  74. cp++;
  75. break;
  76. case '\v':
  77. *cp = 'v';
  78. cp++;
  79. break;
  80. default:
  81. *cp = '?';
  82. cp++;
  83. break;
  84. }
  85. continue;
  86. }
  87. if (c == '\\') {
  88. memmove(cp + 1, cp, strlen(cp) + 1);
  89. *cp = '\\';
  90. cp += 2;
  91. continue;
  92. }
  93. if (c == '"') {
  94. memmove(cp + 1, cp, strlen(cp) + 1);
  95. *cp = '\\';
  96. cp += 2;
  97. continue;
  98. }
  99. if (strchr("[()]{}:;,.<>?!@#$%^&*", c) != NULL) {
  100. cp++;
  101. continue;
  102. }
  103. if (strchr("0123456789", c) != NULL) {
  104. cp++;
  105. continue;
  106. }
  107. if (strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", c) !=
  108. NULL) {
  109. cp++;
  110. continue;
  111. }
  112. // Ok, default to \xHH output.
  113. memmove(cp + 3, cp, strlen(cp) + 1);
  114. char buffer[10];
  115. // int slen =
  116. snprintf(buffer, sizeof(buffer), "\\x%02x", (int)c & 0xff);
  117. /*
  118. if (slen >= sizeof(buffer)) {
  119. ZF_LOGE("snprintf %d > size %d", slen, (int)sizeof(buffer));
  120. }
  121. */
  122. strncpy(cp, buffer, 4);
  123. cp += 4;
  124. continue;
  125. }
  126. return buffer;
  127. }
  128. /*
  129. * strnstr()
  130. *
  131. * buffer safe version that looks for a string.
  132. */
  133. const char *strnstr(const char *source, int len, const char *needle) {
  134. int pos;
  135. for (pos = 0; pos < len; pos++) {
  136. if (source[pos] == needle[0]) {
  137. if (strncmp(source + pos, needle, strlen(needle)) == 0) {
  138. return source + pos;
  139. }
  140. }
  141. }
  142. return NULL;
  143. }
  144. /*
  145. * rstrnstr() Reverse string find in a string
  146. *
  147. * This obeys the len, and handles nulls in buffer.
  148. * find is a c-string (null terminated)
  149. */
  150. int rstrnstr(const char *buffer, int len, const char *find) {
  151. int flen = strlen(find);
  152. if (len < flen) {
  153. // I can't find a string in a buffer smaller then it is!
  154. return -1;
  155. }
  156. int pos = len - flen;
  157. while (pos > 0) {
  158. if (buffer[pos] == find[0]) {
  159. // First chars match, check them all.
  160. if (strncmp(buffer + pos, find, flen) == 0) {
  161. return pos;
  162. }
  163. }
  164. pos--;
  165. }
  166. return -1;
  167. }
  168. /*
  169. * string_insert()
  170. * Inserts a string into a given position.
  171. * This safely checks to make sure the buffer isn't overrun.
  172. *
  173. * buffer is a c null terminated string.
  174. */
  175. int string_insert(char *buffer, size_t max_length, size_t pos,
  176. const char *insert) {
  177. /*
  178. assert(max_length > pos);
  179. assert(buffer != NULL);
  180. assert(insert != NULL);
  181. */
  182. if (pos >= max_length)
  183. return 0;
  184. if (buffer == NULL)
  185. return 0;
  186. if (insert == NULL)
  187. return 0;
  188. if (strlen(insert) == 0)
  189. return 0;
  190. if (pos > strlen(buffer))
  191. return 0;
  192. if (strlen(buffer) + strlen(insert) >= max_length) {
  193. /*
  194. ZF_LOGD("string_insert() failed inserting [%s]", repr(insert));
  195. */
  196. return 0;
  197. }
  198. memmove(buffer + pos + strlen(insert), buffer + pos,
  199. strlen(buffer + pos) + 1);
  200. // cp + strlen(display), cp, strlen(cp) + 1);
  201. strncpy(buffer + pos, insert, strlen(insert));
  202. // (cp, display, strlen(display));
  203. return 1; // success
  204. }
  205. /*
  206. Pascal String Copy. Copy from pascal string, to C String.
  207. First char is pascal string length. (Max 255).
  208. */
  209. void pcopy(char *pstring, char *str) {
  210. int len = (int)*pstring;
  211. strncpy(str, pstring + 1, len);
  212. str[len] = 0;
  213. }
  214. /*
  215. * tail file, return new lines of text.
  216. *
  217. * Only handles lines < 256 chars.
  218. * Does not handle if the file is closed/unlinked/...
  219. *
  220. */
  221. std::string &find_new_text(std::ifstream &infile,
  222. std::streampos &last_position) {
  223. static std::string line;
  224. line.clear();
  225. infile.seekg(0, std::ios::end);
  226. std::streampos filesize = infile.tellg();
  227. if (filesize == -1) {
  228. // Ok, we've failed somehow. Now what?
  229. // cout << "SNAP!";
  230. return line;
  231. }
  232. // check if the new file started
  233. // we don't detect if the file has been unlinked/reset
  234. if (filesize < last_position) {
  235. // cout << "reset! " << filesize << endl;
  236. last_position = 0;
  237. }
  238. while (last_position < filesize) {
  239. // this loop -- seems broken.
  240. // for (long n = last_position; n < filesize; n++) {
  241. infile.seekg(last_position, std::ios::beg);
  242. char test[256];
  243. infile.getline(test, sizeof(test));
  244. if (infile.eof()) {
  245. // We got EOF instead of something.
  246. // Seek back to our last, good, known position
  247. // and exit (wait for the rest of the line)
  248. infile.seekg(last_position, std::ios::beg);
  249. return line;
  250. }
  251. std::streampos new_pos = infile.tellg();
  252. if (new_pos == -1)
  253. return line;
  254. last_position = new_pos;
  255. line.assign(test);
  256. return line;
  257. }
  258. return line;
  259. }
  260. void string_toupper(std::string &str) {
  261. std::transform(str.begin(), str.end(), str.begin(), ::toupper);
  262. }
  263. void string_trim(std::string &value) {
  264. while (*value.begin() == ' ')
  265. value.erase(value.begin());
  266. while (*(value.end() - 1) == ' ')
  267. value.erase(value.end() - 1);
  268. }
  269. std::map<std::string, std::string> read_configfile(std::string filename) {
  270. std::ifstream file(filename);
  271. std::string line;
  272. std::map<std::string, std::string> config;
  273. if (!file.is_open())
  274. return config;
  275. while (std::getline(file, line)) {
  276. if ((line[0] == '#') || (line[0] == ';'))
  277. continue;
  278. if (line.empty())
  279. continue;
  280. // I'm not so sure this part is very good.
  281. std::istringstream is_line(line);
  282. std::string key;
  283. if (std::getline(is_line, key, '=')) {
  284. string_trim(key);
  285. string_toupper(key);
  286. std::string value;
  287. if (std::getline(is_line, value)) {
  288. string_trim(value);
  289. config[key] = value;
  290. /*
  291. std::cout << "Key: [" << key << "] Value: [" << value << "]"
  292. << std::endl;
  293. */
  294. }
  295. }
  296. }
  297. return config;
  298. }
  299. bool replace(std::string &str, const std::string &from, const std::string &to) {
  300. size_t start_pos = str.find(from);
  301. if (start_pos == std::string::npos)
  302. return false;
  303. str.replace(start_pos, from.length(), to);
  304. return true;
  305. }
  306. IConv::IConv(const char *to, const char *from) : ic(iconv_open(to, from)) {}
  307. IConv::~IConv() { iconv_close(ic); }
  308. int IConv::convert(char *input, char *output, size_t outbufsize) {
  309. size_t inbufsize = strlen(input);
  310. // size_t orig_size = outbufsize;
  311. // memset(output, 0, outbufsize);
  312. // https://www.gnu.org/savannah-checkouts/gnu/libiconv/documentation/libiconv-1.15/iconv.3.html
  313. int r = iconv(ic, &input, &inbufsize, &output, &outbufsize);
  314. *output = 0;
  315. return r;
  316. }
  317. static IConv converter("UTF-8", "CP437");
  318. static time_t last_time = 0;
  319. std::map<std::string, std::string> CONFIG = read_configfile("hharry.cfg");
  320. /*
  321. * harry_level:
  322. *
  323. * 0 - inactive
  324. * 1 - Week 1 (1-7)
  325. * 2 - Week 2 (8-14)
  326. * 3 - Week 3 (15-21)
  327. * 4 - Week 4 (22-31)
  328. */
  329. int harry_level(void) {
  330. struct tm *tmp;
  331. time_t now = time(NULL);
  332. static int last = 0;
  333. auto search = CONFIG.find("LEVEL");
  334. if (search != CONFIG.end()) {
  335. last = stoi(search->second);
  336. if (last > 4) {
  337. last = 4;
  338. }
  339. if (last < 0) {
  340. last = 0;
  341. }
  342. return last;
  343. }
  344. if (last_time < now + 10) {
  345. last_time = now;
  346. // Do our every 10 second checks here
  347. tmp = gmtime(&now);
  348. if (tmp->tm_mon != 9)
  349. return (last = 0);
  350. if (tmp->tm_mday < 8)
  351. return (last = 1);
  352. if (tmp->tm_mday < 15)
  353. return (last = 2);
  354. if (tmp->tm_mday < 22)
  355. return (last = 3);
  356. return (last = 4);
  357. }
  358. return last;
  359. }
  360. /*
  361. * This is similar to repr, but --
  362. *
  363. * It converts high ASCII to UTF8, so it will display correctly
  364. * in the logfiles!
  365. */
  366. const char *logrepr(const char *input) {
  367. static char buffer[10240];
  368. char *cp;
  369. strcpy(buffer, input);
  370. cp = buffer;
  371. while (*cp != 0) {
  372. unsigned char c = *cp;
  373. if (c == ' ') {
  374. cp++;
  375. continue;
  376. };
  377. /* Ok, it's form-feed ('\f'), newline ('\n'), carriage return ('\r'),
  378. * horizontal tab ('\t'), and vertical tab ('\v') */
  379. if (strchr("\f\n\r\t\v", c) != NULL) {
  380. memmove(cp + 1, cp, strlen(cp) + 1);
  381. *cp = '\\';
  382. cp++;
  383. switch (c) {
  384. case '\f':
  385. *cp = 'f';
  386. cp++;
  387. break;
  388. case '\n':
  389. *cp = 'n';
  390. cp++;
  391. break;
  392. case '\r':
  393. *cp = 'r';
  394. cp++;
  395. break;
  396. case '\t':
  397. *cp = 't';
  398. cp++;
  399. break;
  400. case '\v':
  401. *cp = 'v';
  402. cp++;
  403. break;
  404. /* default:
  405. *cp = '?';
  406. cp++;
  407. break; */
  408. }
  409. continue;
  410. }
  411. if (c == '\\') {
  412. memmove(cp + 1, cp, strlen(cp) + 1);
  413. *cp = '\\';
  414. cp += 2;
  415. continue;
  416. }
  417. if (c == '"') {
  418. memmove(cp + 1, cp, strlen(cp) + 1);
  419. *cp = '\\';
  420. cp += 2;
  421. continue;
  422. }
  423. if (strchr("[()]{}:;,.<>?!@#$%^&*", c) != NULL) {
  424. cp++;
  425. continue;
  426. }
  427. if (strchr("0123456789", c) != NULL) {
  428. cp++;
  429. continue;
  430. }
  431. if (strchr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", c) !=
  432. NULL) {
  433. cp++;
  434. continue;
  435. }
  436. if ((int)c < 0x20) {
  437. // Ok, default to \xHH output.
  438. memmove(cp + 3, cp, strlen(cp) + 1);
  439. char buffer[10];
  440. // int slen =
  441. snprintf(buffer, sizeof(buffer), "\\x%02x", (int)c & 0xff);
  442. strncpy(cp, buffer, 4);
  443. cp += 4;
  444. continue;
  445. };
  446. cp++;
  447. continue;
  448. }
  449. static char fancybuffer[16384];
  450. converter.convert(buffer, fancybuffer, sizeof(fancybuffer));
  451. return fancybuffer;
  452. }