mystic.cpp 31 KB

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