mystic.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075
  1. #include <assert.h>
  2. #include <fcntl.h>
  3. #include <pty.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <termios.h>
  7. #include <unistd.h>
  8. #include <sys/select.h>
  9. #include <sys/wait.h>
  10. // #include <signal.h> // handle Ctrl-C/SIGINT
  11. #include <strings.h> // strcasecmp
  12. #include <time.h> // usleep(), nanonsleep() ?
  13. #include <ctype.h>
  14. #include <stdlib.h> // random()
  15. #include <regex.h>
  16. /* Log level guideline:
  17. * - ZF_LOG_FATAL - happened something impossible and absolutely unexpected.
  18. * Process can't continue and must be terminated.
  19. * Example: division by zero, unexpected modifications from other thread.
  20. * - ZF_LOG_ERROR - happened something possible, but highly unexpected. The
  21. * process is able to recover and continue execution.
  22. * Example: out of memory (could also be FATAL if not handled properly).
  23. * - ZF_LOG_WARN - happened something that *usually* should not happen and
  24. * significantly changes application behavior for some period of time.
  25. * Example: configuration file not found, auth error.
  26. * - ZF_LOG_INFO - happened significant life cycle event or major state
  27. * transition.
  28. * Example: app started, user logged in.
  29. * - ZF_LOG_DEBUG - minimal set of events that could help to reconstruct the
  30. * execution path. Usually disabled in release builds.
  31. * - ZF_LOG_VERBOSE - all other events. Usually disabled in release builds.
  32. *
  33. * *Ideally*, log file of debugged, well tested, production ready application
  34. * should be empty or very small. Choosing a right log level is as important as
  35. * providing short and self descriptive log message.
  36. */
  37. /*
  38. #define ZF_LOG_VERBOSE 1
  39. #define ZF_LOG_DEBUG 2
  40. #define ZF_LOG_INFO 3
  41. #define ZF_LOG_WARN 4
  42. #define ZF_LOG_ERROR 5
  43. #define ZF_LOG_FATAL 6
  44. */
  45. // LOGGING with file output
  46. #include "zf_log.h"
  47. FILE *g_log_file;
  48. static void file_output_callback(const zf_log_message *msg, void *arg) {
  49. (void)arg;
  50. *msg->p = '\n';
  51. fwrite(msg->buf, msg->p - msg->buf + 1, 1, g_log_file);
  52. fflush(g_log_file);
  53. }
  54. static void file_output_close(void) { fclose(g_log_file); }
  55. static void file_output_open(const char *const log_path) {
  56. g_log_file = fopen(log_path, "a");
  57. if (!g_log_file) {
  58. ZF_LOGW("Failed to open log file %s", log_path);
  59. return;
  60. }
  61. atexit(file_output_close);
  62. zf_log_set_output_v(ZF_LOG_PUT_STD, 0, file_output_callback);
  63. }
  64. #include "terminal.h"
  65. struct console_details console;
  66. #include "utils.h"
  67. // END LOGGING
  68. #include "lastseen.h"
  69. /*
  70. What is the name of the actual, real Mystic executable
  71. that we'll be executing and mangling?
  72. */
  73. #define TARGET "./mySTIC"
  74. // Size of our input and output buffers.
  75. #define BSIZE 1024
  76. /*
  77. * string_insert()
  78. * Inserts a string into a given position.
  79. * This safely checks to make sure the buffer isn't overrun.
  80. */
  81. int string_insert(char *buffer, int max_length, int pos, const char *insert) {
  82. assert(max_length > pos);
  83. assert(buffer != NULL);
  84. assert(insert != NULL);
  85. if (strlen(buffer) + strlen(insert) >= max_length) {
  86. ZF_LOGD("string_insert() failed inserting [%s]", repr(insert));
  87. return 0;
  88. }
  89. memmove(buffer + pos + strlen(insert), buffer + pos,
  90. strlen(buffer + pos) + 1);
  91. // cp + strlen(display), cp, strlen(cp) + 1);
  92. strncpy(buffer + pos, insert, strlen(insert));
  93. // (cp, display, strlen(display));
  94. return 1; // success
  95. }
  96. // Should this be passed around to the functions that use it?
  97. #include "render.h"
  98. /*
  99. These are harry "timeout" events.
  100. These happen when we've been sitting around awhile.
  101. */
  102. #ifdef CPP_MADMAN_STL_CODE
  103. const char *random_phrase(const char *words, int len, int last_seen) {
  104. // ooh. a map of char *s to last_seen_events. :P
  105. static map<const char *, array<int>> tracker;
  106. map<const char *, array<int>>::iterator it;
  107. array<int, last_seen> it = tracker.find(words);
  108. if (it == tracker.end()) {
  109. // key does not exist.
  110. array<int, last_seen> last;
  111. for (int i = 0; i < last_seen; i++) {
  112. last[i] = -1;
  113. };
  114. tracker.insert(words, last);
  115. it = tracker.find(words);
  116. };
  117. }
  118. #endif
  119. void harry_idle_event(int fd) {
  120. // Make something happen
  121. char buffer[100];
  122. int r;
  123. // This is no where near finished, BUT!
  124. const char *phrases[] = {"Hahaha", "Snicker, snicker", "Boo!",
  125. "MeOW", "I see U", "Arrooo!",
  126. "Ahh-wooo!", "Aaaooo!"};
  127. const char *cp;
  128. static LastSeen last_seen_harry_event(2);
  129. // Remember the last phrase used,
  130. // and don't repeat (the last two)!
  131. do {
  132. r = randint((sizeof(phrases) / sizeof(char *)));
  133. // r = random() % ((sizeof(phrases) / sizeof(char *)) - 1);
  134. } while (last_seen_harry_event.seen_before(r));
  135. // ZF_LOGD("%d => %d %d", r, last_seen_harry_event[0],
  136. // last_seen_harry_event[1]);
  137. cp = phrases[r];
  138. int color = random() % 15 + 1;
  139. /*
  140. int color = random() % 16;
  141. if (color == 0) {
  142. color++;
  143. } // If it's 0 let's make it 1. // color = (random() % 15) + 1
  144. */
  145. sprintf(buffer, "^S2^C%02d%s^P2^CR^D%02d", color, cp, (int)strlen(cp));
  146. ZF_LOGD("harry_event: render(%d, \"%s\")", fd, buffer);
  147. render(fd, buffer, strlen(buffer));
  148. }
  149. void init_harry() {
  150. // init_have_seen(last_seen_harry_event, MAX_HARRY_EVENT_DUPS);
  151. // ZF_LOGD("init => %d %d", last_seen_harry_event[0],
  152. // last_seen_harry_event[1]);
  153. console_init(&console);
  154. }
  155. /*
  156. The code to get the username and fullname is useless on telnet
  157. connections.
  158. */
  159. const char *username = NULL;
  160. const char *fullname = NULL;
  161. /*
  162. Pascal String Copy. Copy from pascal string, to C String.
  163. First char is pascal string length. (Max 255).
  164. */
  165. void pcopy(char *pstring, char *str) {
  166. int len = (int)*pstring;
  167. strncpy(str, pstring + 1, len);
  168. str[len] = 0;
  169. }
  170. /*
  171. This only works for those few idiots that use the
  172. horribly broken SSH crap that Mystic uses.
  173. */
  174. int locate_user(const char *alias) {
  175. FILE *user;
  176. char buffer[0x600];
  177. char temp[100];
  178. user = fopen("data/users.dat", "rb");
  179. if (user == NULL)
  180. return 0;
  181. // Carry on!
  182. while (fread(buffer, 0x600, 1, user) == 1) {
  183. pcopy(buffer + 0x6d, temp);
  184. if (strcasecmp(temp, username) == 0) {
  185. pcopy(buffer + 0x8c, temp);
  186. fullname = strdup(temp);
  187. break;
  188. }
  189. /*
  190. printf("Alias: %s\n", temp);
  191. pcopy(buffer + 0x8c, temp );
  192. printf("Full Name: %s\n", temp );
  193. */
  194. }
  195. fclose(user);
  196. return 1;
  197. }
  198. // Buffers are BSIZE + 1, so a buffer that size can strcpy safely.
  199. regex_t ANSI;
  200. regex_t WORDS;
  201. regex_t WORD;
  202. int init_regex(void) {
  203. int ret;
  204. char ansi[] = "\x1b\[[0-9]+(;[0-9]+)*?[a-zA-Z]";
  205. char words[] = "[a-zA-Z]+( [a-zA-Z]+)+";
  206. char word[] = "[a-zA-Z]+";
  207. char errorbuf[100];
  208. if (ret = regcomp(&ANSI, ansi, REG_EXTENDED | REG_NEWLINE)) {
  209. regerror(ret, &ANSI, errorbuf, sizeof(errorbuf));
  210. ZF_LOGW("Regex %s failed to compile: %s", ansi, errorbuf);
  211. return 0;
  212. };
  213. if (ret = regcomp(&WORDS, words, REG_EXTENDED | REG_NEWLINE)) {
  214. regerror(ret, &WORDS, errorbuf, sizeof(errorbuf));
  215. ZF_LOGW("Regex %s failed to compile: %s", words, errorbuf);
  216. return 0;
  217. };
  218. if (ret = regcomp(&WORD, word, REG_EXTENDED | REG_NEWLINE)) {
  219. regerror(ret, &WORD, errorbuf, sizeof(errorbuf));
  220. ZF_LOGW("Regex %s failed to compile: %s", word, errorbuf);
  221. return 0;
  222. };
  223. return 1;
  224. }
  225. int regmatch(regex_t *preg, const char *string, size_t nmatch,
  226. regmatch_t pmatch[], int eflags) {
  227. // returns number of matches found. (Max nmatch)
  228. int matches = 0;
  229. int offset = 0;
  230. while (matches < nmatch) {
  231. int ret = regexec(preg, string + offset, nmatch - matches, pmatch + matches,
  232. eflags);
  233. if (!ret) {
  234. int current = offset;
  235. offset += pmatch[matches].rm_eo;
  236. pmatch[matches].rm_so += current;
  237. pmatch[matches].rm_eo += current;
  238. matches++;
  239. } else if (ret == REG_NOMATCH) {
  240. break;
  241. } else {
  242. break;
  243. }
  244. }
  245. return matches;
  246. }
  247. #define MAX_MATCH 32
  248. regmatch_t rxmatch[MAX_MATCH];
  249. int rx_match(regex_t *regex, const char *buffer) {
  250. int ret;
  251. ret = regmatch(regex, buffer, MAX_MATCH, rxmatch, 0);
  252. if (0) {
  253. for (int i = 0; i < ret; i++) {
  254. ZF_LOGI("%d : (%d-%d)", i, rxmatch[i].rm_so, rxmatch[i].rm_eo);
  255. }
  256. }
  257. return ret;
  258. }
  259. /**
  260. * random_activate()
  261. *
  262. * Is a weight (1-10),
  263. * tests if random number is < weight * 10.
  264. *
  265. * So random_activate(9) happens more frequently
  266. * then random_activate(8) or lower.
  267. *
  268. * This probably needs to be fixed.
  269. * We need a better randint(RANGE) code.
  270. */
  271. int random_activate(int w) {
  272. int r = randint(100);
  273. if (r <= (w * 10)) {
  274. return 1;
  275. };
  276. return 0;
  277. }
  278. /*
  279. word_state(): // deprecated
  280. -1 only lower
  281. +1 only upper
  282. 0 mixed
  283. */
  284. int word_state(const char *buffer, int len) {
  285. int p;
  286. int upper = 0;
  287. int lower = 0;
  288. int ret;
  289. float pct;
  290. for (p = 0; p < len; p++) {
  291. char c = buffer[p];
  292. if (isalpha(c)) {
  293. if (isupper(c)) {
  294. upper++;
  295. };
  296. if (islower(c)) {
  297. lower++;
  298. };
  299. }
  300. }
  301. if (upper == lower) {
  302. return 0;
  303. }
  304. if (upper > lower) {
  305. ret = 1;
  306. pct = ((float)lower / (float)upper) * 100.0;
  307. } else {
  308. ret = -1;
  309. pct = ((float)upper / (float)lower) * 100.0;
  310. }
  311. // ZF_LOGD("So far %d with %f %%", ret, pct);
  312. if (pct < 40.0) {
  313. return ret;
  314. }
  315. return 0;
  316. }
  317. /*
  318. Given a buffer and length, mangle away.
  319. toupper, tolower, flipper
  320. */
  321. int word_mangler(char *buffer, int len) {
  322. int p;
  323. int count = 0;
  324. int state;
  325. // state = word_state(buffer, len);
  326. // ZF_LOGD("word_state(%.*s) %d", len, buffer, state);
  327. state = randrange(-1, 1);
  328. // TODO: Transposer
  329. for (p = 0; p < len; p++) {
  330. char c = buffer[p];
  331. if (randint(len) == p) {
  332. break;
  333. }
  334. switch (state) {
  335. case -1:
  336. // upper
  337. if (islower(c)) {
  338. count++;
  339. buffer[p] = toupper(c);
  340. }
  341. break;
  342. case 1:
  343. // lower
  344. if (isupper(c)) {
  345. count++;
  346. buffer[p] = tolower(c);
  347. }
  348. break;
  349. case 0:
  350. // flipper
  351. if (islower(c)) {
  352. count++;
  353. buffer[p] = toupper(c);
  354. } else {
  355. if (isupper(c)) {
  356. count++;
  357. buffer[p] = tolower(c);
  358. }
  359. }
  360. break;
  361. }
  362. }
  363. return count;
  364. }
  365. int word_wrangler(char *buffer, int len) {
  366. int p;
  367. int count;
  368. int state;
  369. // state = word_state(buffer, len);
  370. // ZF_LOGD("word_state(%.*s) %d", len, buffer, state);
  371. if (len < 5) {
  372. return 0;
  373. }
  374. p = randint(len - 4) + 2;
  375. for (count = 0; count < 4; count++) {
  376. if (!isalpha(buffer[p + count]))
  377. break;
  378. }
  379. ZF_LOGV_MEM(buffer, len, "wrangler %d len %d:", p, count);
  380. if (count >= 2) {
  381. for (int x = 0; x < count / 2; x++) {
  382. char ch = buffer[p + x];
  383. buffer[p + x] = buffer[p + count - 1 - x];
  384. buffer[p + count - 1 - x] = ch;
  385. }
  386. ZF_LOGV_MEM(buffer, len, "word now:");
  387. return 1;
  388. } else
  389. return 0;
  390. }
  391. int buffer_insert(char *buffer, int len, int max_length, int pos,
  392. const char *insert) {
  393. if (len + strlen(insert) > max_length) {
  394. ZF_LOGD("buffer_insert failed [%s]", repr(insert));
  395. return 0;
  396. }
  397. memmove(buffer + pos + strlen(insert), buffer + pos, len - pos);
  398. strncpy(buffer + pos, insert, strlen(insert));
  399. return 1;
  400. }
  401. /*
  402. * The buffer that we've been given is much larger now.
  403. *
  404. * We can no longer mangle or insert into the given buffer.
  405. * Why? Because we don't know what is behind it now!
  406. */
  407. int mangle(int fd, const char *buffer, int len) {
  408. int x, i;
  409. int need_render = 0; // changing word case around doesn't need the render
  410. int mangled = 0;
  411. int mangled_chars = 0;
  412. char play[BSIZE * 2];
  413. const char *cp;
  414. // Make a copy of buffer, since it can no longer be changed
  415. // inserted into.
  416. memcpy(play, buffer, len);
  417. // NEVER reference buffer from this point on!
  418. char work[BSIZE * 2];
  419. // Use terminal - clean out ANSI
  420. // ZF_LOGI("mangle:");
  421. ZF_LOGI_MEM(play, len, "Mangle (%u bytes):", len);
  422. // strcpy(work, buffer);
  423. /*
  424. NOTE: We copy the buffer, so we can clear out ANSI codes, etc.
  425. Otherwise we might mess some ANSI up in the manglying
  426. process.
  427. */
  428. /*
  429. (random) Look for ANSI CLS and:
  430. display random spooky texts around, with delays ... then CLS.
  431. display ANSI graphic file, with delays ... then CLS
  432. */
  433. const char *ANSI_CLS = "\x1b[2J";
  434. cp = strnstr(play, len, ANSI_CLS); // strstr(buffer, ANSI_CLS);
  435. if (cp != NULL) {
  436. static int ANSI_CLS_count = 0; // count the number we've seen
  437. ZF_LOGI("seen: ANSI_CLS");
  438. ANSI_CLS_count++;
  439. // Don't activate on the very first CLS. Too soon, don't screw up the ANSI
  440. // detection.
  441. if (ANSI_CLS_count > 1) {
  442. // Ok, figure out the restore color, just in case
  443. struct console_details temp_console;
  444. // Make exact copy of our current console state.
  445. memcpy(&temp_console, &console, sizeof(console));
  446. // Play the buffer into the console
  447. console_receive(&temp_console, play, cp - play);
  448. char restore_color[30]; // ansi color
  449. strcpy(restore_color, color_restore(&temp_console));
  450. if (random_activate(3)) {
  451. char display[100] = "";
  452. int needs_cls = 0;
  453. struct file_need {
  454. const char *filename;
  455. int cls;
  456. int rand_pos;
  457. } possibles[] = {
  458. {"goofy_head", 1, 0}, {"bat", 1, 0}, {"panther", 1, 0},
  459. {"wolf", 1, 0}, {"skull", 0, 1}, {"skull2", 0, 1},
  460. {"guy", 0, 1}, {"blinkman", 0, 1}, {"ghost", 1, 0}};
  461. static LastSeen last_files(2);
  462. int r;
  463. do {
  464. r = randint((sizeof(possibles) / sizeof(file_need)));
  465. } while (last_files.seen_before(r));
  466. int x, y;
  467. x = randint(50) + 1;
  468. y = randint(12) + 1;
  469. char fgoto[10];
  470. if (possibles[r].rand_pos) {
  471. sprintf(fgoto, "^f%02d%02d", x, y);
  472. } else {
  473. strcpy(fgoto, "^F");
  474. }
  475. // (2); // (sizeof(possibles) / sizeof(file_need)) - 1);
  476. needs_cls = possibles[r].cls;
  477. // I get what's happening. Mystic moves cursor to home, CLS, cursor
  478. // home. When we get here, we're ALWAYS at the top of the screen...
  479. // Hence our bat isn't displayed at the end of the screen.
  480. // This is before the actual CLS, so we CLS before displaying our files.
  481. // I tried a ^P2 before doing this .. but I'd rather have the picture up
  482. // right away I think.
  483. sprintf(display, "%s%s%s.^P3%s", needs_cls ? "\x1b[2J" : "", fgoto,
  484. possibles[r].filename, restore_color);
  485. ZF_LOGI("mangle(ANSI_CLS): %d file inserted %s", r, repr(display));
  486. // Move the buffer so there's room for the display string.
  487. if (buffer_insert(play, len, sizeof(play), cp - play, display)) {
  488. len += strlen(display);
  489. // if (string_insert(buffer, 1024, cp - buffer, display)) {
  490. ZF_LOGI_MEM(play, len, "mangle(ANSI_CLS) (%u bytes):", len);
  491. // ZF_LOGI("mangle(ANSI_CLS):");
  492. // ZF_LOGI_REPR(buffer);
  493. // ZF_LOGI("mangle(ANSI_CLS): [%s]", repr(buffer));
  494. need_render = 1;
  495. /*
  496. Copy the new buffer over, but hide our "render" code
  497. from the remaining mangler steps.
  498. */
  499. memcpy(work, play, len);
  500. // strcpy(work, buffer);
  501. i = cp - play;
  502. // find offset into "buffer"
  503. // apply to work.
  504. memset(work + i, ' ', strlen(display));
  505. } else {
  506. ZF_LOGD("insert failed [%s].", repr(display));
  507. }
  508. } else {
  509. if (random_activate(4)) {
  510. int r;
  511. char display[100] = "";
  512. const char *phrasing[] = {"^R1Haha^P1ha^P1ha", "Poof!", "Got U",
  513. "Anyone there?", "^R1Knock, ^P1Knock"};
  514. static LastSeen last_phrasing(2);
  515. ZF_LOGI("mangle(ANSI_CLS)");
  516. // sprintf( display, "^P2...");
  517. // This string actually screws up ANSI detection (takes too long)
  518. // strcpy(display, "^P2^S501234567890^P1abcdef^P2g^P3h^P4i^S0^P2");
  519. // strcpy(display, "^P2^S301234^P15^S0^P2");
  520. // Add in random text, plus color!
  521. do {
  522. r = random() % ((sizeof(phrasing) / sizeof(char *)) - 1);
  523. } while (last_phrasing.seen_before(r));
  524. int color = random() % 15 + 1;
  525. int x = random() % 30 + 1;
  526. int y = random() % 15 + 1;
  527. /*
  528. Don't have it pause there before moving the cursor.
  529. Move the cursor, get the color changed, THEN pause.
  530. Then act all crazy.
  531. NOTE: Make sure if you use any ^R Render effects, turn them off
  532. before trying to display the restore_color. :P ^R0 Also, make
  533. sure you re-home the cursor ^G0101 because that's where they are
  534. expecting the cursor to be! (At least it's how Mystic does it.)
  535. HOME, CLS, HOME, ... Not sure what others do there. We'll see.
  536. */
  537. sprintf(display, "^G%02d%02d^S3^C%02d^P1%s^S0^R0%s^P1^G0101", x, y,
  538. color, phrasing[r], restore_color);
  539. // sprintf(display, "^P1^S3^C%02d%s^S0^R0%s^P1", color, phrasing[r],
  540. // restore_color);
  541. // ZF_LOGI("mangle(ANSI_CLS): Inserted (%02d) %s", color,
  542. // phrasing[r]);
  543. ZF_LOGI_MEM(play, len, "mangle(ANSI_CLS) :");
  544. // Move the buffer so there's room for the display string.
  545. if (buffer_insert(play, len, sizeof(play), cp - play, display)) {
  546. len += strlen(display);
  547. // if (string_insert(buffer, BSIZE * 4, cp - buffer, display)) {
  548. ZF_LOGI_MEM(play, len, "mangle(ANSI_CLS) + :");
  549. // ZF_LOGI("mangle(ANSI_CLS):");
  550. // ZF_LOGI_REPR(buffer);
  551. need_render = 1;
  552. /*
  553. Copy the new buffer over, but hide our "render" code
  554. from the remaining mangler steps.
  555. */
  556. memcpy(work, play, len);
  557. // strcpy(work, buffer);
  558. i = cp - play;
  559. // find offset into "buffer"
  560. // apply to work.
  561. memset(work + i, ' ', strlen(display));
  562. } else {
  563. ZF_LOGD("insert failed [%s].", repr(display));
  564. }
  565. }
  566. }
  567. }
  568. }
  569. memcpy(work, play, len);
  570. // strcpy(work, buffer); // sure.
  571. const char replace_with = ' ';
  572. for (x = 0; x < len; x++) {
  573. int ansi = console_char(&console, play[x]);
  574. if (ansi) {
  575. work[x] = replace_with;
  576. }
  577. // fixup "work" so it's a valid C string
  578. if (buffer[x] == 0) {
  579. work[x] = replace_with;
  580. }
  581. }
  582. // fixup "work" buffer so it's a valid c string
  583. // (required for regex to work.)
  584. work[len] = 0;
  585. ZF_LOGI_MEM(work, len, "Work now:");
  586. /*
  587. (random) Locate words (in work), and possibly flip them around.
  588. Transpose words. Transpose case. Transpose letters.
  589. Ok, what would be interesting, is if we could find
  590. W\x1[0;34mORDS with color changes in them, and work with them.
  591. without screwing up the color changes, of course. :P
  592. Example:
  593. Y\x1b[0;1mes \x1b[0;1;34m\x1b[0;1;34;44m N\x1b[0;1;44mo
  594. Yes No
  595. ^ This would be a job for a crazy regex.
  596. I'd have to map the characters to positions in the buffer. :S
  597. I'd want mangle and wrangle to work.
  598. The Message menu -- doesn't hardly get mangled at all (at least on
  599. my test site). Because all of the color changes break up the
  600. words in the menu.
  601. */
  602. x = rx_match(&WORDS, work);
  603. ZF_LOGD("found %d word groups", x);
  604. if (x > 0) {
  605. for (i = 0; i < x; i++) {
  606. // Yes! Be random!
  607. if (random_activate(8)) {
  608. int c = word_mangler(play + rxmatch[i].rm_so,
  609. rxmatch[i].rm_eo - rxmatch[i].rm_so);
  610. if (c) {
  611. mangled++;
  612. mangled_chars += c;
  613. }
  614. }
  615. if (random_activate(4)) {
  616. word_wrangler(play + rxmatch[i].rm_so,
  617. rxmatch[i].rm_eo - rxmatch[i].rm_so);
  618. }
  619. }
  620. }
  621. /*
  622. (random) Locate single words, and transpose words.
  623. Transpose letters.
  624. */
  625. /*
  626. (random) Display up to certain point. Delay.
  627. Print some characters slowly. Delay.
  628. */
  629. if (need_render) {
  630. ZF_LOGD_MEM(play, len, "Ready to render:");
  631. // ZF_LOGD("HH %d : (%d) %s", need_render, (int)strlen(buffer),
  632. // repr(buffer));
  633. } else {
  634. if (mangled) {
  635. ZF_LOGD_MEM(play, len, "Mangled %d words, %d chars:", mangled,
  636. mangled_chars);
  637. /* ZF_LOGD("Mangled %d words, %d chars : %s", mangled, mangled_chars,
  638. repr(buffer)); */
  639. }
  640. }
  641. if (need_render) {
  642. render(fd, play, len);
  643. } else {
  644. write(fd, play, len); // strlen(buffer));
  645. };
  646. return need_render && mangled;
  647. }
  648. int harry_happens(time_t *last_event, int wakeup) {
  649. time_t now = time(NULL);
  650. int elapsed = now - *last_event;
  651. if (elapsed > wakeup) {
  652. // Ok! It's been too long since we've done something.
  653. *last_event = now;
  654. return 1;
  655. }
  656. return 0;
  657. }
  658. /*
  659. TO FIX: Stop using c strings, must use char * buffer + int length.
  660. MAY CONTAIN NULL VALUES.
  661. Rework some things here.
  662. Here's the "plan":
  663. if buffer is EMPTY:
  664. time_idle = 1;
  665. // setup for "random timeout value mess"
  666. // we're in luck! The last parameter is time interval/timeout. :D
  667. timeout.tv_sec = 10; // randrange(10-25)
  668. timeout.tv_usec = 0;
  669. NOT EMPTY:
  670. // we're in luck! The last parameter is time interval/timeout. :D
  671. timeout.tv_sec = 0;
  672. timeout.tv_usec = 10; // Wild Guess Here? Maybe higher, maybe lower?
  673. time_idle = 0;
  674. ON READ:
  675. read/append to current buffer.
  676. We can't use nulls -- what if they are using ZModem, there's nulls in the
  677. file! Look for trailing / the very last "\r\n".
  678. (I could mangle/chunk it line by line. But I'm not sure I'd need to do
  679. that.)
  680. Optional "mangle" buffer up to that very point -- and send up to that point.
  681. Option #2: Maybe we send everything if program has been running for under
  682. 20 seconds. This would allow the ANSI detect to not get screwed up by this
  683. new idea.
  684. ON TIMEOUT:
  685. if time_idle:
  686. Activate funny harry timeout events.
  687. else:
  688. Ok, we *STILL* haven't received any more characters into the buffer --
  689. even after waiting. (Maybe we haven't waited long enough?)
  690. send the pending information in the buffer and clear it out.
  691. Maybe this is a prompt, and there won't be a \r\n.
  692. This allows for cleaner process of "lines" of buffer. We shouldn't break
  693. in the midDLE OF A WORD. Downside is that we sit on buffer contents a little
  694. while / some amount of time -- which will add some lag to prompts showing up.
  695. ZModem:
  696. start: "rz^M**"...
  697. 05-12 18:12:15.916 >> rz^M**^XB00000000000000^M<8A>^Q
  698. 05-12 18:12:15.928 << **\x18B0100000023be50\r\n\x11
  699. 05-12 18:12:15.928 >> *^XC^D
  700. 05-12 18:12:15.939 << **\x18B0900000000a87c\r\n\x11
  701. 05-12 18:12:15.940 >> *^XC
  702. # Start of PK zipfile.
  703. 05-12 18:12:15.941 >> PK^C^D^T
  704. end:
  705. 05-12 18:26:38.700 << **\x18B0100000023be50\r\n\x11
  706. 05-12 18:26:38.700 >> **^XB0823a77600344c^M<8A>
  707. 05-12 18:26:38.711 << **\x18B0800000000022d\r\n
  708. 05-12 18:26:38.712 >> OO^MESC[0m
  709. */
  710. int main(int argc, char *argv[]) {
  711. int master;
  712. pid_t pid;
  713. int node = -1;
  714. file_output_open("horrible_harry.log");
  715. init_harry();
  716. srandom(time(NULL));
  717. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown
  718. // -Ubugz -PUWISHPASSWORD
  719. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  720. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown
  721. // -Ubugz -PUWISH
  722. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  723. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  724. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML0 -SL1 -ST0 -CUnknown
  725. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown
  726. // -Ubugz -PDUMBWAYTODOTHIS
  727. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML1 -SL1 -ST2 -CUnknown
  728. // -Ubugz -PIDONTUSEPASCAL
  729. // SSH: -ML1 -ST2
  730. // Telnet: -ML0 -ST0
  731. // Locate username (if given) in the command line
  732. // -U<username>
  733. for (int x = 0; x < argc; x++) {
  734. if (strncmp("-U", argv[x], 2) == 0) {
  735. username = argv[x] + 2;
  736. ZF_LOGI("Username: [%s]", username);
  737. };
  738. if (strncmp("-SL", argv[x], 3) == 0) {
  739. node = argv[x][3] - '0' + 1;
  740. ZF_LOGI("Node: %d", node);
  741. }
  742. }
  743. if (username != NULL) {
  744. locate_user(username);
  745. ZF_LOGD("Username: [%s] A.K.A. [%s]", username, fullname);
  746. }
  747. if (!init_regex())
  748. return 2;
  749. pid = forkpty(&master, NULL, NULL, NULL);
  750. // impossible to fork
  751. if (pid < 0) {
  752. return 1;
  753. }
  754. // child
  755. else if (pid == 0) {
  756. char *args[20]; // max 20 args
  757. int x;
  758. char new_exec[] = TARGET;
  759. args[0] = new_exec;
  760. for (x = 1; x < argc; x++) {
  761. args[x] = argv[x];
  762. };
  763. args[x] = NULL;
  764. // run Mystic, run!
  765. execvp(TARGET, args);
  766. }
  767. // parent
  768. else {
  769. struct termios tios, orig1;
  770. struct timeval timeout;
  771. time_t last_event = 0; // time(NULL);
  772. ZF_LOGD("starting");
  773. tcgetattr(master, &tios);
  774. tios.c_lflag &= ~(ECHO | ECHONL | ICANON);
  775. /*
  776. tios.c_iflag &= ~(ICRNL | IXON | BRKINT);
  777. tios.c_iflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  778. tios.c_oflag &= ~(OPOST);
  779. */
  780. tcsetattr(master, TCSAFLUSH, &tios);
  781. tcgetattr(1, &orig1);
  782. tios = orig1;
  783. tios.c_iflag &= ~(ICRNL | IXON | BRKINT);
  784. tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  785. tios.c_oflag &= ~(OPOST);
  786. // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
  787. tcsetattr(1, TCSAFLUSH, &tios);
  788. char buffer[BSIZE + 1];
  789. int size = 0;
  790. for (;;) {
  791. int time_idle;
  792. // define estruturas para o select, que serve para verificar qual
  793. // se tornou "pronto pra uso"
  794. fd_set read_fd;
  795. fd_set write_fd;
  796. fd_set except_fd;
  797. // inicializa as estruturas
  798. FD_ZERO(&read_fd);
  799. FD_ZERO(&write_fd);
  800. FD_ZERO(&except_fd);
  801. // atribui o descritor master, obtido pelo forkpty, ao read_fd
  802. FD_SET(master, &read_fd);
  803. // atribui o stdin ao read_fd
  804. FD_SET(STDIN_FILENO, &read_fd);
  805. // o descritor tem que ser unico para o programa, a documentacao
  806. // recomenda um calculo entre os descritores sendo usados + 1
  807. /*
  808. TODO: Figure out how this would work.
  809. I'm thinking something like timeouts 30-50 seconds?
  810. And as we get closer, 15-25 seconds.
  811. */
  812. if (size == 0) {
  813. // buffer is empty
  814. timeout.tv_sec = randrange(10, 20);
  815. timeout.tv_usec = 0;
  816. time_idle = 1;
  817. } else {
  818. // buffer is not empty
  819. timeout.tv_sec = 0;
  820. timeout.tv_usec = 1;
  821. time_idle = 0;
  822. }
  823. if (select(master + 1, &read_fd, &write_fd, &except_fd, &timeout) == 0) {
  824. ZF_LOGI("TIMEOUT");
  825. // This means timeout!
  826. if (time_idle) {
  827. harry_idle_event(STDOUT_FILENO);
  828. } else {
  829. ZF_LOGV_MEM(buffer, size, "TIMEOUT buffer size=%d", size);
  830. console_receive(&console, buffer, size);
  831. write(STDOUT_FILENO, buffer, size);
  832. size = 0;
  833. // buffer is empty now
  834. }
  835. }
  836. /*
  837. static char output[(BSIZE * 4) + 1];
  838. */
  839. int total;
  840. // read_fd esta atribuido com read_fd?
  841. if (FD_ISSET(master, &read_fd)) {
  842. // leia o que bc esta mandando
  843. // ZF_LOGD("read (%d) %d bytes", size, BSIZE - size);
  844. if ((total = read(master, buffer + size, BSIZE - size)) != -1) {
  845. // Ok, we've read more into the buffer.
  846. ZF_LOGV_MEM(buffer + size, total, "Read %d bytes:", total);
  847. size += total;
  848. ZF_LOGV_MEM(buffer, size, "Buffer now:");
  849. int pos = rstrnstr(buffer, size, "\r\n");
  850. if (pos >= 0) {
  851. // found something!
  852. pos += 2;
  853. ZF_LOGD_MEM(buffer, pos, "mangle buffer %d bytes:", pos);
  854. mangle(STDOUT_FILENO, buffer, pos);
  855. memmove(buffer, buffer + pos, size - pos);
  856. size -= pos;
  857. } else {
  858. ZF_LOGV("position of /r/n not found.");
  859. }
  860. } else
  861. break;
  862. }
  863. // read_fd esta atribuido com a entrada padrao?
  864. if (FD_ISSET(STDIN_FILENO, &read_fd)) {
  865. // leia a entrada padrao
  866. char input[BSIZE];
  867. int r = read(STDIN_FILENO, &input, BSIZE);
  868. input[r] = 0;
  869. // e escreva no bc
  870. ZF_LOGI("<< %s", repr(input));
  871. write(master, &input, r);
  872. // This is INPUT from the USER
  873. // ZF_LOGI_MEM( input, strlen(input), "<< ");
  874. }
  875. }
  876. // Restore terminal
  877. tcsetattr(1, TCSAFLUSH, &orig1);
  878. ZF_LOGD("exit");
  879. }
  880. return 0;
  881. }