mystic.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <unistd.h> // usleep()
  4. #include <fcntl.h>
  5. #include <pty.h>
  6. #include <termios.h>
  7. #include <sys/select.h>
  8. #include <sys/wait.h>
  9. // #include <signal.h> // handle Ctrl-C/SIGINT
  10. #include <strings.h> // strcasecmp
  11. #include <time.h> // usleep(), nanonsleep() ?
  12. #include <ctype.h>
  13. #include <stdlib.h> // random()
  14. #include <regex.h>
  15. /* Log level guideline:
  16. * - ZF_LOG_FATAL - happened something impossible and absolutely unexpected.
  17. * Process can't continue and must be terminated.
  18. * Example: division by zero, unexpected modifications from other thread.
  19. * - ZF_LOG_ERROR - happened something possible, but highly unexpected. The
  20. * process is able to recover and continue execution.
  21. * Example: out of memory (could also be FATAL if not handled properly).
  22. * - ZF_LOG_WARN - happened something that *usually* should not happen and
  23. * significantly changes application behavior for some period of time.
  24. * Example: configuration file not found, auth error.
  25. * - ZF_LOG_INFO - happened significant life cycle event or major state
  26. * transition.
  27. * Example: app started, user logged in.
  28. * - ZF_LOG_DEBUG - minimal set of events that could help to reconstruct the
  29. * execution path. Usually disabled in release builds.
  30. * - ZF_LOG_VERBOSE - all other events. Usually disabled in release builds.
  31. *
  32. * *Ideally*, log file of debugged, well tested, production ready application
  33. * should be empty or very small. Choosing a right log level is as important as
  34. * providing short and self descriptive log message.
  35. */
  36. /*
  37. #define ZF_LOG_VERBOSE 1
  38. #define ZF_LOG_DEBUG 2
  39. #define ZF_LOG_INFO 3
  40. #define ZF_LOG_WARN 4
  41. #define ZF_LOG_ERROR 5
  42. #define ZF_LOG_FATAL 6
  43. */
  44. // LOGGING with file output
  45. #include "zf_log.h"
  46. FILE *g_log_file;
  47. static void file_output_callback(const zf_log_message *msg, void *arg) {
  48. (void)arg;
  49. *msg->p = '\n';
  50. fwrite(msg->buf, msg->p - msg->buf + 1, 1, g_log_file);
  51. fflush(g_log_file);
  52. }
  53. static void file_output_close(void) { fclose(g_log_file); }
  54. static void file_output_open(const char *const log_path) {
  55. g_log_file = fopen(log_path, "a");
  56. if (!g_log_file) {
  57. ZF_LOGW("Failed to open log file %s", log_path);
  58. return;
  59. }
  60. atexit(file_output_close);
  61. zf_log_set_output_v(ZF_LOG_PUT_STD, 0, file_output_callback);
  62. }
  63. /**
  64. * Display a repr of the given string.
  65. *
  66. * This converts most \n\r\v\f\t codes,
  67. * defaults to \xHH (hex value).
  68. */
  69. const char *repr(const char *data) {
  70. static char buffer[4096];
  71. char *cp;
  72. strcpy(buffer, data);
  73. cp = buffer;
  74. while (*cp != 0) {
  75. char c = *cp;
  76. if (isspace(c)) {
  77. if (c == ' ') {
  78. cp++;
  79. continue;
  80. };
  81. /* Ok, it's form-feed ('\f'), newline ('\n'), carriage return ('\r'),
  82. * horizontal tab ('\t'), and vertical tab ('\v') */
  83. memmove(cp + 1, cp, strlen(cp) + 1);
  84. *cp = '\\';
  85. cp++;
  86. switch (c) {
  87. case '\f':
  88. *cp = 'f';
  89. cp++;
  90. break;
  91. case '\n':
  92. *cp = 'n';
  93. cp++;
  94. break;
  95. case '\r':
  96. *cp = 'r';
  97. cp++;
  98. break;
  99. case '\t':
  100. *cp = 't';
  101. cp++;
  102. break;
  103. case '\v':
  104. *cp = 'v';
  105. cp++;
  106. break;
  107. default:
  108. *cp = '?';
  109. cp++;
  110. break;
  111. }
  112. continue;
  113. }
  114. if (isprint(c)) {
  115. cp++;
  116. continue;
  117. };
  118. // Ok, default to \xHH output.
  119. memmove(cp + 3, cp, strlen(cp) + 1);
  120. *cp = '\\';
  121. cp++;
  122. *cp = 'x';
  123. cp++;
  124. char buffer[3];
  125. sprintf(buffer, "%02x", (int)c & 0xff);
  126. *cp = buffer[0];
  127. cp++;
  128. *cp = buffer[1];
  129. cp++;
  130. continue;
  131. }
  132. return buffer;
  133. }
  134. #define CHUNKSIZE 32
  135. void zf_repr_chunk(int LOG_LEVEL, const char *chunk) {
  136. const char *output = repr(chunk);
  137. ZF_LOG_WRITE(LOG_LEVEL, _ZF_LOG_TAG, "r\"%s\"", output);
  138. }
  139. void zf_repr(int LOG_LEVEL, const char *string) {
  140. // Chunks -- 32?
  141. char buffer[CHUNKSIZE + 1];
  142. int pos = 0;
  143. int len = strlen(string);
  144. while (len > CHUNKSIZE) {
  145. strncpy(buffer, string + pos, CHUNKSIZE);
  146. buffer[CHUNKSIZE] = 0;
  147. pos += CHUNKSIZE;
  148. len -= CHUNKSIZE;
  149. zf_repr_chunk(LOG_LEVEL, buffer);
  150. };
  151. if (len > 0) {
  152. strcpy(buffer, string + pos);
  153. zf_repr_chunk(LOG_LEVEL, buffer);
  154. }
  155. }
  156. // Here's my idea for debugging
  157. #define ZF_LOGV_REPR(str) zf_repr(ZF_LOG_VERBOSE, str)
  158. #define ZF_LOGD_REPR(str) zf_repr(ZF_LOG_DEBUG, str)
  159. #define ZF_LOGI_REPR(str) zf_repr(ZF_LOG_INFO, str)
  160. #define ZF_LOGW_REPR(str) zf_repr(ZF_LOG_WARN, str)
  161. #define ZF_LOGE_REPR(str) zf_repr(ZF_LOG_ERROR, str)
  162. #define ZF_LOGF_REPR(str) zf_repr(ZF_LOG_FATAL, str)
  163. // END LOGGING
  164. #include "lastseen.h"
  165. // http://c-faq.com/lib/randrange.html
  166. int randint(int N) { return rand() / (RAND_MAX / N + 1); }
  167. // http://c-faq.com/lib/randrange.html
  168. // numbers in the range [M, N] could be generated with something like
  169. int randrange(int M, int N) {
  170. return M + rand() / (RAND_MAX / (N - M + 1) + 1);
  171. }
  172. /*
  173. What is the name of the actual, real Mystic executable
  174. that we'll be executing and mangling?
  175. */
  176. #define TARGET "./mySTIC"
  177. // Size of our input and output buffers.
  178. #define BSIZE 128
  179. /*
  180. * string_insert()
  181. * Inserts a string into a given position.
  182. * This safely checks to make sure the buffer isn't overrun.
  183. */
  184. int string_insert(char *buffer, int max_length, int pos, const char *insert) {
  185. if (strlen(buffer) + strlen(insert) >= max_length) {
  186. ZF_LOGD("string_insert() failed inserting [%s]", repr(insert));
  187. return 0;
  188. }
  189. memmove(buffer + pos + strlen(insert), buffer + pos,
  190. strlen(buffer + pos) + 1);
  191. // cp + strlen(display), cp, strlen(cp) + 1);
  192. strncpy(buffer + pos, insert, strlen(insert));
  193. // (cp, display, strlen(display));
  194. return 1; // success
  195. }
  196. // Should this be passed around to the functions that use it?
  197. struct render {
  198. int speed;
  199. int effect;
  200. } current_render;
  201. int render_overlimit = 0;
  202. void reset_render(void) {
  203. current_render.speed = 0;
  204. current_render.effect = 0;
  205. render_overlimit = 0;
  206. }
  207. #define TRIGGER "^"
  208. // Max limit we'll sleep before ignoring effects/speed.
  209. #define SLEEP_LIMIT 30
  210. int ms_sleep(unsigned int ms) {
  211. int result = 0;
  212. struct timespec ts = {ms / 1000, (ms % 1000) * 1000000L};
  213. do {
  214. struct timespec ts_sleep = ts;
  215. result = nanosleep(&ts_sleep, &ts);
  216. } while ((-1 == result));
  217. return result;
  218. }
  219. void render_sleep(void) {
  220. if (render_overlimit)
  221. return;
  222. if (current_render.speed) { // * 100 still too slow.
  223. ms_sleep(current_render.speed * 10);
  224. }
  225. }
  226. /*
  227. Terminal tracking
  228. Actually, I believe I only really need to track the color information.
  229. Everything else, I'm not sure I really care about.
  230. */
  231. struct console_details {
  232. int posx, posy;
  233. int savedx, savedy;
  234. char ansi[20]; // current ANSI command being processed.
  235. int in_ansi;
  236. int fgcolor; // 0-7 // not 0-15
  237. int bgcolor; // 0-7
  238. int status; // 0, 1 or 5 (Blink)
  239. } console;
  240. void console_init(struct console_details *cdp) {
  241. cdp->posx = 0;
  242. cdp->posy = 0;
  243. cdp->savedx = 0;
  244. cdp->savedy = 0;
  245. cdp->in_ansi = 0;
  246. cdp->fgcolor = 7;
  247. cdp->bgcolor = 0;
  248. cdp->status = 0;
  249. }
  250. void ansi_color(struct console_details *cdp, int color) {
  251. // ZF_LOGV("ansi_color(%d)", color);
  252. if (color == 0) {
  253. cdp->status = 0;
  254. cdp->fgcolor = 7;
  255. cdp->bgcolor = 0;
  256. return;
  257. }
  258. if (color == 1) {
  259. cdp->status = 1;
  260. return;
  261. }
  262. if (color == 5) {
  263. cdp->status = 5;
  264. return;
  265. }
  266. if ((color >= 30) && (color <= 37)) {
  267. cdp->fgcolor = color - 30;
  268. return;
  269. }
  270. if ((color >= 40) && (color <= 47)) {
  271. cdp->bgcolor = color - 40;
  272. return;
  273. }
  274. ZF_LOGD("ansi_color( %d ) is unknown to me.", color);
  275. }
  276. const char *color_restore(struct console_details *cdp) {
  277. static char buffer[30];
  278. if (cdp->status == 0) {
  279. sprintf(buffer, "\x1b[0;3%d;4%dm", cdp->fgcolor, cdp->bgcolor);
  280. } else {
  281. sprintf(buffer, "\x1b[0;%d;3%d;4%dm", cdp->status, cdp->fgcolor,
  282. cdp->bgcolor);
  283. };
  284. return buffer;
  285. }
  286. void console_ansi(struct console_details *cdp, const char *ansi) {
  287. int understood = 0;
  288. const char *cp = ansi;
  289. const char *last = ansi + strlen(ansi) - 1;
  290. int number, number2;
  291. if (*cp == '\x1b') {
  292. cp++;
  293. // Ok, that's expected.
  294. if (*cp == '[') {
  295. cp++;
  296. // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
  297. switch (*last) {
  298. case 'A':
  299. // cursor up
  300. if (cp == last) {
  301. number = 1;
  302. } else {
  303. number = atoi(cp);
  304. if (number < 1) {
  305. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi),
  306. number);
  307. number = 1;
  308. }
  309. };
  310. cdp->posy -= number;
  311. if (cdp->posy < 0) {
  312. cdp->posy = 0;
  313. ZF_LOGD(
  314. "console_ansi( %s ): attempt to move above top of screen (%d)",
  315. repr(ansi), number);
  316. }
  317. understood = 1;
  318. return;
  319. case 'B':
  320. // cursor down
  321. if (cp == last) {
  322. number = 1;
  323. } else {
  324. number = atoi(cp);
  325. if (number < 1) {
  326. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi),
  327. number);
  328. number = 1;
  329. }
  330. };
  331. cdp->posy += number;
  332. // check range/"scroll"
  333. understood = 1;
  334. return;
  335. case 'C':
  336. // cursor forward
  337. if (cp == last) {
  338. number = 1;
  339. } else {
  340. number = atoi(cp);
  341. if (number < 1) {
  342. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi),
  343. number);
  344. number = 1;
  345. }
  346. };
  347. cdp->posx += number;
  348. // Well. According to the "spec", the screen limits are hard
  349. // If the cursor is already at the edge of the screen, this has no
  350. // effect. ^ This is *NOT* how any ANSI BBS terminal program acts!
  351. while (cdp->posx > 79) {
  352. cdp->posy++;
  353. // check range/"scroll"
  354. cdp->posx -= 79;
  355. }
  356. understood = 1;
  357. return;
  358. case 'D':
  359. // cursor backwards
  360. if (cp == last) {
  361. number = 1;
  362. } else {
  363. number = atoi(cp);
  364. if (number < 1) {
  365. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi),
  366. number);
  367. number = 0;
  368. }
  369. };
  370. cdp->posx -= number;
  371. // Well. According to the "spec", the screen limits are hard
  372. // If the cursor is already at the edge of the screen, this has no
  373. // effect. ^ This is *NOT* how any ANSI BBS terminal program acts!
  374. while (cdp->posx < 0) {
  375. cdp->posy--;
  376. if (cdp->posy < 0) {
  377. cdp->posy = 0;
  378. }
  379. cdp->posx += 79;
  380. }
  381. understood = 1;
  382. return;
  383. case 'H':
  384. // cursor position
  385. if (*cp == ';') {
  386. // Missing first number
  387. number = 1;
  388. cp++;
  389. if (cp == last) {
  390. // missing 2nd number as well?
  391. number2 = 1;
  392. } else {
  393. number2 = atoi(cp);
  394. }
  395. } else {
  396. // Ok, find the first number
  397. number = atoi(cp);
  398. cp = strchr(cp, ';');
  399. if (cp == NULL) {
  400. // Missing 2nd number
  401. number2 = 1;
  402. } else {
  403. // 2nd number found, maybe.
  404. cp++;
  405. if (cp == last) {
  406. number2 = 1;
  407. } else {
  408. number2 = atoi(cp);
  409. }
  410. }
  411. }
  412. // Our positions start at zero, not one.
  413. cdp->posx = number - 1;
  414. cdp->posy = number2 - 1;
  415. understood = 1;
  416. break;
  417. case 'J':
  418. // clear
  419. if (cp == last) {
  420. number = 0;
  421. } else {
  422. number = atoi(cp);
  423. };
  424. // clears ... part of the screen.
  425. if (number == 2) {
  426. cdp->posx = 0;
  427. cdp->posy = 0;
  428. };
  429. understood = 1;
  430. break;
  431. case 'm':
  432. // color
  433. if (cp == last) {
  434. // nothing given, default to 0.
  435. number = 0;
  436. ansi_color(cdp, number);
  437. } else {
  438. while (cp != last) {
  439. number = atoi(cp);
  440. ansi_color(cdp, number);
  441. cp++;
  442. while ((cp != last) && (isdigit(*cp))) {
  443. cp++;
  444. };
  445. if (cp != last) {
  446. if (*cp == ';') {
  447. cp++;
  448. }
  449. }
  450. }
  451. }
  452. understood = 1;
  453. break;
  454. case 't':
  455. case 'r':
  456. case 'h':
  457. case '!':
  458. // These are ones that I don't care about.
  459. case 'n': // This is terminal detect -- give me cursor position
  460. understood = 1;
  461. break;
  462. default:
  463. // unsure -- possibly not important
  464. ZF_LOGD("console_ansi( %s ): ???", repr(ansi));
  465. understood = 0;
  466. }
  467. }
  468. };
  469. if (!understood) {
  470. ZF_LOGD("console_ansi( %s ): was not understood.", repr(ansi));
  471. }
  472. }
  473. /*
  474. * console_char()
  475. * return whether or not we are still in_ansi
  476. */
  477. int console_char(struct console_details *cdp, char ch) {
  478. char *cp;
  479. if (cdp->in_ansi) {
  480. // Ok, append this char
  481. cp = cdp->ansi + strlen(cdp->ansi);
  482. *cp = ch;
  483. cp++;
  484. *cp = 0;
  485. if (isalpha(ch)) {
  486. // Ok!
  487. console_ansi(cdp, cdp->ansi);
  488. cdp->in_ansi = 0;
  489. cdp->ansi[0] = 0;
  490. return 1;
  491. }
  492. return 1;
  493. } else {
  494. if (ch == '\x1b') {
  495. cp = cdp->ansi;
  496. *cp = ch;
  497. cp++;
  498. *cp = 0;
  499. cdp->in_ansi = 1;
  500. return 1;
  501. }
  502. if (ch == '\r') {
  503. // Carriage return
  504. cdp->posx = 0;
  505. return 0;
  506. }
  507. if (ch == '\n') {
  508. cdp->posy++;
  509. // check range/"scroll"
  510. return 0;
  511. }
  512. if (ch == '\b') {
  513. // Backspace.
  514. if (cdp->posx > 0) {
  515. cdp->posx--;
  516. }
  517. return 0;
  518. }
  519. if (ch == '\f') {
  520. // form feed
  521. // treat as clear screen
  522. cdp->posx = 0;
  523. cdp->posy = 0;
  524. return 0;
  525. }
  526. /*
  527. I don't believe that anything else can possibly be here, other then an
  528. actual printable character. So!
  529. */
  530. cdp->posx++;
  531. if (cdp->posx > 79) {
  532. cdp->posx = 0;
  533. cdp->posy++;
  534. // check range/"scroll"
  535. }
  536. return 0;
  537. }
  538. }
  539. void console_string(struct console_details *cdp, const char *chars) {
  540. int x;
  541. for (x = 0; x < strlen(chars); x++) {
  542. console_char(cdp, chars[x]);
  543. }
  544. }
  545. void console_receive(struct console_details *cdp, const char *chars, int len) {
  546. int x;
  547. for (x = 0; x < len; x++) {
  548. console_char(cdp, chars[x]);
  549. }
  550. }
  551. /*
  552. Well SNAP! Mystic numbers don't remotely match ANSI color codes.
  553. 00 : Sets the current foreground to Black 0;30
  554. 01 : Sets the current foreground to Dark Blue 0;34
  555. 02 : Sets the current foreground to Dark Green 0;32
  556. 03 : Sets the current foreground to Dark Cyan 0;36
  557. 04 : Sets the current foreground to Dark Red 0;31
  558. 05 : Sets the current foreground to Dark Magenta 0;35
  559. 06 : Sets the current foreground to Brown 0;33
  560. 07 : Sets the current foreground to Grey 0;37
  561. 08 : Sets the current foreground to Dark Grey 1;30
  562. 09 : Sets the current foreground to Light Blue 1;34
  563. 10 : Sets the current foreground to Light Green 1;32
  564. 11 : Sets the current foreground to Light Cyan 1;36
  565. 12 : Sets the current foreground to Light Red 1;31
  566. 13 : Sets the current foreground to Light Magenta 1;35
  567. 14 : Sets the current foreground to Yellow 1;33
  568. 15 : Sets the current foreground to White 1;37
  569. 16 : Sets the current background to Black 40
  570. 17 : Sets the current background to Blue 44
  571. 18 : Sets the current background to Green 42
  572. 19 : Sets the current background to Cyan 46
  573. 20 : Sets the current background to Red 41
  574. 21 : Sets the current background to Magenta 45
  575. 22 : Sets the current background to Brown 43
  576. 23 : Sets the current background to Grey 47
  577. 24 : Sets the current background to black with blinking foreground 5;40
  578. 25 : Sets the current background to blue with blinking foreground 5;44
  579. 26 : Sets the current background to green with blinking foreground 5;42
  580. 27 : Sets the current background to cyan with blinking foreground 5;46
  581. 28 : Sets the current background to red with blinking foreground 5;41
  582. 29 : Sets the current background to magenta with blinking foreground 5;45
  583. 30 : Sets the current background to brown with blinking foreground 5;43
  584. 31 : Sets the current background to grey with blinking foreground 5;47
  585. Other things that Mystic does ...
  586. [A## - Move the cursor up ## lines
  587. [B## - Move the cursor down ## lines
  588. [C## - Move the cursor forward (to the right) ## columns
  589. [D## - Move the cursor backwards (to the left) ## columns
  590. [K - Clear from the current cursor position to the end of the line
  591. [L - Move cursor and erase data backwards from current column to column ##
  592. [X## - Move cursor to X coordinate ##
  593. [Y## - Move cursor to Y coordinate ##
  594. BS - Sends 1 destructive backspace sequence (ASCII 8-32-8)
  595. CL - Clears the screen (ANSI 1,1 locate and [2J or ASCII 12)
  596. CR - Send a carrage return and line feed (move to next line)
  597. RA - Restore the saved text attribute color
  598. RS - Restore the saved user's terminal screen
  599. SA - Save the current text attribute color
  600. SS - Save the entire user's terminal screen
  601. */
  602. // Covert MYSTIC color to (Proper) ANSI COLOR.
  603. const int MYSTIC[] = {0, 4, 2, 6, 1, 5, 3, 7};
  604. // ANSI_color = MYSTIC[ odd_mystic_color % 8 ]
  605. void write_color(int fd, int color) {
  606. char buffer[12];
  607. switch (color) {
  608. case 0:
  609. case 1:
  610. case 2:
  611. case 3:
  612. case 4:
  613. case 5:
  614. case 6:
  615. case 7:
  616. sprintf(buffer, "\x1b[0;3%dm", MYSTIC[color]);
  617. break;
  618. case 8:
  619. case 9:
  620. case 10:
  621. case 11:
  622. case 12:
  623. case 13:
  624. case 14:
  625. case 15:
  626. sprintf(buffer, "\x1b[0;1;3%dm", MYSTIC[color - 8]);
  627. break;
  628. case 16:
  629. case 17:
  630. case 18:
  631. case 19:
  632. case 20:
  633. case 21:
  634. case 22:
  635. case 23:
  636. sprintf(buffer, "\x1b[4%dm", MYSTIC[color - 16]);
  637. break;
  638. case 24:
  639. case 25:
  640. case 26:
  641. case 27:
  642. case 28:
  643. case 29:
  644. case 30:
  645. case 31:
  646. sprintf(buffer, "\x1b[5;4%dm", MYSTIC[color - 24]);
  647. break;
  648. default:
  649. buffer[0] = 0;
  650. break;
  651. }
  652. ZF_LOGD("write_color( %d ): %s", color, repr(buffer));
  653. write(fd, buffer, strlen(buffer));
  654. }
  655. int send_file(int fd, char *filename) {
  656. FILE *fp;
  657. char buffer[100];
  658. int read;
  659. fp = fopen(filename, "rb");
  660. if (fp == NULL) {
  661. ZF_LOGD("Failed to open %s", filename);
  662. return 0;
  663. }
  664. while ((read = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
  665. write(fd, buffer, read);
  666. };
  667. fclose(fp);
  668. return 1;
  669. }
  670. /**
  671. * process_trigger( fd, *cp )
  672. *
  673. * This process a command trigger.
  674. * It has seen TRIGGER, and now it is
  675. * processing whatever comes after it.
  676. * It will perform the process, and
  677. * return the char * of whatever is next.
  678. */
  679. const char *process_trigger(int fd, const char *cp) {
  680. char ch;
  681. int i, x, y;
  682. ch = toupper(*cp);
  683. cp++;
  684. switch (ch) {
  685. case 'D':
  686. i = 0;
  687. if (isdigit(*cp)) {
  688. i = (*cp) - '0';
  689. cp++;
  690. };
  691. if (isdigit(*cp)) {
  692. i *= 10;
  693. i += (*cp) - '0';
  694. cp++;
  695. };
  696. if ((i > 0) && (i < 80)) {
  697. ZF_LOGI("DEL %02d", i);
  698. for (x = 0; x < i; x++) {
  699. write(fd, "\b \b", 3);
  700. }
  701. };
  702. break;
  703. case 'C': {
  704. i = 0;
  705. if (*cp == 'R') {
  706. cp++;
  707. const char *restore = color_restore(&console);
  708. write(fd, restore, strlen(restore));
  709. break;
  710. }
  711. if (isdigit(*cp)) {
  712. i = (*cp) - '0';
  713. cp++;
  714. };
  715. if (isdigit(*cp)) {
  716. i *= 10;
  717. i += (*cp) - '0';
  718. cp++;
  719. };
  720. write_color(fd, i);
  721. } break;
  722. case 'F': {
  723. // Ok, look for filename
  724. char ansifile[32] = "./hh/";
  725. char *ap = ansifile + strlen(ansifile);
  726. while (*cp != '.') {
  727. *ap = *cp;
  728. ap++;
  729. *ap = 0;
  730. cp++;
  731. };
  732. strcat(ansifile, ".ans");
  733. cp++;
  734. ZF_LOGD("FILE [%s]", ansifile);
  735. send_file(fd, ansifile);
  736. } break;
  737. case 'G': {
  738. x = 0;
  739. if (isdigit(*cp)) {
  740. x = (*cp) - '0';
  741. cp++;
  742. };
  743. if (isdigit(*cp)) {
  744. x *= 10;
  745. x += (*cp) - '0';
  746. cp++;
  747. };
  748. y = 0;
  749. if (isdigit(*cp)) {
  750. y = (*cp) - '0';
  751. cp++;
  752. };
  753. if (isdigit(*cp)) {
  754. y *= 10;
  755. y += (*cp) - '0';
  756. cp++;
  757. };
  758. char buffer[20]; // row ; column H
  759. ZF_LOGD("GOTO (%d,%d)", x, y);
  760. sprintf(buffer, "\x1b[%d;%dH", y, x);
  761. write(fd, buffer, strlen(buffer));
  762. } break;
  763. case 'R': {
  764. i = 0;
  765. if (isdigit(*cp)) {
  766. i = (*cp) - '0';
  767. cp++;
  768. };
  769. if ((i > 0) && (i < 10)) {
  770. ZF_LOGI("RENDER %d", i);
  771. current_render.effect = i;
  772. } else {
  773. current_render.effect = 0;
  774. }
  775. } break;
  776. case 'S': {
  777. i = 0;
  778. if (isdigit(*cp)) {
  779. i = (*cp) - '0';
  780. cp++;
  781. };
  782. if ((i > 0) && (i < 10)) {
  783. ZF_LOGI("SPEED %d", i);
  784. current_render.speed = i;
  785. } else {
  786. current_render.speed = 0;
  787. }
  788. } break;
  789. case 'P': {
  790. i = 0;
  791. if (isdigit(*cp)) {
  792. i = (*cp) - '0';
  793. cp++;
  794. };
  795. if ((i > 0) && (i < 10)) {
  796. ZF_LOGI("PAWS %d", i);
  797. // sleep(i);
  798. if (!render_overlimit) {
  799. sleep(i);
  800. };
  801. }
  802. } break;
  803. }
  804. return cp;
  805. }
  806. /**
  807. * render_effect( fd, ch )
  808. *
  809. * Displays the given character with whatever
  810. * rendering effect is currently active.
  811. * (If any).
  812. */
  813. void render_effect(int fd, char ch) {
  814. int effect = current_render.effect;
  815. int l;
  816. char space = ' ';
  817. char bs = '\b';
  818. switch (effect) {
  819. case 1:
  820. // CHAR + SPC + BS
  821. render_sleep();
  822. write(fd, &ch, 1);
  823. render_sleep();
  824. write(fd, &space, 1);
  825. render_sleep();
  826. render_sleep();
  827. write(fd, &bs, 1);
  828. break;
  829. case 2:
  830. // CHAR + 8 spaces + 8 BS
  831. render_sleep();
  832. write(fd, &ch, 1);
  833. for (l = 0; l < 8; l++) {
  834. render_sleep();
  835. write(fd, &space, 1);
  836. }
  837. for (l = 0; l < 8; l++) {
  838. render_sleep();
  839. write(fd, &bs, 1);
  840. }
  841. break;
  842. case 0:
  843. default:
  844. // NORMAL
  845. render_sleep();
  846. write(fd, &ch, 1);
  847. break;
  848. }
  849. }
  850. /**
  851. * render( fd, string_out )
  852. *
  853. * Render an entire string.
  854. * Handles TRIGGER.
  855. * Renders with effects.
  856. */
  857. void render(int fd, const char *string_out) {
  858. const char *cp = string_out;
  859. const char *trigger = cp;
  860. time_t start = time(NULL);
  861. int elapsed;
  862. int over = 0;
  863. reset_render();
  864. ZF_LOGD("render(%d, %s)", fd, repr(string_out));
  865. // Check our time from time to time.
  866. // If we start running long, disable sleeps.
  867. while ((trigger = strstr(cp, TRIGGER)) != NULL) {
  868. // There is special things to handle in here.
  869. while (cp != trigger) {
  870. elapsed = time(NULL) - start;
  871. if (elapsed > SLEEP_LIMIT) {
  872. render_overlimit = 1;
  873. current_render.speed = 0;
  874. };
  875. // write(fd, cp, 1 );
  876. render_effect(fd, *cp);
  877. cp++;
  878. };
  879. // ZF_LOGI( "at trigger: (%s)", cp);
  880. cp += strlen(TRIGGER);
  881. // Ok, we're pointing at the trigger -- do something.
  882. cp = process_trigger(fd, cp);
  883. // ZF_LOGI( "after trigger: (%s)", cp);
  884. };
  885. // We still might be under a rendering effect.
  886. while (*cp != 0) {
  887. elapsed = time(NULL) - start;
  888. if (elapsed > SLEEP_LIMIT) {
  889. render_overlimit = 1;
  890. current_render.speed = 0;
  891. };
  892. // write(fd, cp, 1);
  893. render_effect(fd, *cp);
  894. cp++;
  895. }
  896. }
  897. /*
  898. These are harry "timeout" events.
  899. These happen when we've been sitting around awhile.
  900. */
  901. #ifdef CPP_MADMAN_STL_CODE
  902. const char *random_phrase(const char *words, int len, int last_seen) {
  903. // ooh. a map of char *s to last_seen_events. :P
  904. static map<const char *, array<int>> tracker;
  905. map<const char *, array<int>>::iterator it;
  906. array<int, last_seen> it = tracker.find(words);
  907. if (it == tracker.end()) {
  908. // key does not exist.
  909. array<int, last_seen> last;
  910. for (int i = 0; i < last_seen; i++) {
  911. last[i] = -1;
  912. };
  913. tracker.insert(words, last);
  914. it = tracker.find(words);
  915. };
  916. }
  917. #endif
  918. void harry_idle_event(int fd) {
  919. // Make something happen
  920. char buffer[100];
  921. int r;
  922. // This is no where near finished, BUT!
  923. const char *phrases[] = {"Hahaha", "Snicker, snicker", "Boo!",
  924. "MeOW", "I see U", "Arrooo!",
  925. "Ahh-wooo!", "Aaaooo!"};
  926. const char *cp;
  927. static LastSeen last_seen_harry_event(2);
  928. // Remember the last phrase used,
  929. // and don't repeat (the last two)!
  930. do {
  931. r = randint((sizeof(phrases) / sizeof(char *)));
  932. // r = random() % ((sizeof(phrases) / sizeof(char *)) - 1);
  933. } while (last_seen_harry_event.seen_before(r));
  934. // ZF_LOGD("%d => %d %d", r, last_seen_harry_event[0],
  935. // last_seen_harry_event[1]);
  936. cp = phrases[r];
  937. int color = random() % 15 + 1;
  938. /*
  939. int color = random() % 16;
  940. if (color == 0) {
  941. color++;
  942. } // If it's 0 let's make it 1. // color = (random() % 15) + 1
  943. */
  944. sprintf(buffer, "^S2^C%02d%s^P2^CR^D%02d", color, cp, (int)strlen(cp));
  945. ZF_LOGD("harry_event: render(%d, \"%s\")", fd, buffer);
  946. render(fd, buffer);
  947. }
  948. void init_harry() {
  949. // init_have_seen(last_seen_harry_event, MAX_HARRY_EVENT_DUPS);
  950. // ZF_LOGD("init => %d %d", last_seen_harry_event[0],
  951. // last_seen_harry_event[1]);
  952. console_init(&console);
  953. }
  954. /*
  955. The code to get the username and fullname is useless on telnet
  956. connections.
  957. */
  958. const char *username = NULL;
  959. const char *fullname = NULL;
  960. /*
  961. Pascal String Copy. Copy from pascal string, to C String.
  962. First char is pascal string length. (Max 255).
  963. */
  964. void pcopy(char *pstring, char *str) {
  965. int len = (int)*pstring;
  966. strncpy(str, pstring + 1, len);
  967. str[len] = 0;
  968. }
  969. /*
  970. This only works for those few idiots that use the
  971. horribly broken SSH crap that Mystic uses.
  972. */
  973. int locate_user(const char *alias) {
  974. FILE *user;
  975. char buffer[0x600];
  976. char temp[100];
  977. user = fopen("data/users.dat", "rb");
  978. if (user == NULL)
  979. return 0;
  980. // Carry on!
  981. while (fread(buffer, 0x600, 1, user) == 1) {
  982. pcopy(buffer + 0x6d, temp);
  983. if (strcasecmp(temp, username) == 0) {
  984. pcopy(buffer + 0x8c, temp);
  985. fullname = strdup(temp);
  986. break;
  987. }
  988. /*
  989. printf("Alias: %s\n", temp);
  990. pcopy(buffer + 0x8c, temp );
  991. printf("Full Name: %s\n", temp );
  992. */
  993. }
  994. fclose(user);
  995. return 1;
  996. }
  997. // Buffers are BSIZE + 1, so a buffer that size can strcpy safely.
  998. regex_t ANSI;
  999. regex_t WORDS;
  1000. regex_t WORD;
  1001. int init_regex(void) {
  1002. int ret;
  1003. char ansi[] = "\x1b\[[0-9]+(;[0-9]+)*?[a-zA-Z]";
  1004. char words[] = "[a-zA-Z]+( [a-zA-Z]+)+";
  1005. char word[] = "[a-zA-Z]+";
  1006. char errorbuf[100];
  1007. if (ret = regcomp(&ANSI, ansi, REG_EXTENDED | REG_NEWLINE)) {
  1008. regerror(ret, &ANSI, errorbuf, sizeof(errorbuf));
  1009. ZF_LOGW("Regex %s failed to compile: %s", ansi, errorbuf);
  1010. return 0;
  1011. };
  1012. if (ret = regcomp(&WORDS, words, REG_EXTENDED | REG_NEWLINE)) {
  1013. regerror(ret, &WORDS, errorbuf, sizeof(errorbuf));
  1014. ZF_LOGW("Regex %s failed to compile: %s", words, errorbuf);
  1015. return 0;
  1016. };
  1017. if (ret = regcomp(&WORD, word, REG_EXTENDED | REG_NEWLINE)) {
  1018. regerror(ret, &WORD, errorbuf, sizeof(errorbuf));
  1019. ZF_LOGW("Regex %s failed to compile: %s", word, errorbuf);
  1020. return 0;
  1021. };
  1022. return 1;
  1023. }
  1024. int regmatch(regex_t *preg, const char *string, size_t nmatch,
  1025. regmatch_t pmatch[], int eflags) {
  1026. // returns number of matches found. (Max nmatch)
  1027. int matches = 0;
  1028. int offset = 0;
  1029. int ret;
  1030. while (matches < nmatch) {
  1031. ret = regexec(preg, string + offset, nmatch - matches, pmatch + matches,
  1032. eflags);
  1033. if (!ret) {
  1034. int current = offset;
  1035. offset += pmatch[matches].rm_eo;
  1036. pmatch[matches].rm_so += current;
  1037. pmatch[matches].rm_eo += current;
  1038. matches++;
  1039. } else if (ret == REG_NOMATCH) {
  1040. break;
  1041. } else {
  1042. break;
  1043. }
  1044. }
  1045. return matches;
  1046. }
  1047. #define MAX_MATCH 32
  1048. regmatch_t rxmatch[MAX_MATCH];
  1049. int rx_match(regex_t *regex, const char *buffer) {
  1050. int ret;
  1051. ret = regmatch(regex, buffer, MAX_MATCH, rxmatch, 0);
  1052. if (0) {
  1053. for (int i = 0; i < ret; i++) {
  1054. ZF_LOGI("%d : (%d-%d)", i, rxmatch[i].rm_so, rxmatch[i].rm_eo);
  1055. }
  1056. }
  1057. return ret;
  1058. }
  1059. /*
  1060. Terminal processing section.
  1061. Monitor lines, position, color.
  1062. What screen size do I want to emulate?
  1063. ANSI codes.
  1064. Do I need this??
  1065. */
  1066. /**
  1067. * random_activate()
  1068. *
  1069. * Is a weight (1-10),
  1070. * tests if random number is < weight * 10.
  1071. *
  1072. * So random_activate(9) happens more frequently
  1073. * then random_activate(8) or lower.
  1074. *
  1075. * This probably needs to be fixed.
  1076. * We need a better randint(RANGE) code.
  1077. */
  1078. int random_activate(int w) {
  1079. int r = random() % 100;
  1080. if (r <= (w * 10)) {
  1081. return 1;
  1082. };
  1083. return 0;
  1084. }
  1085. /*
  1086. word_state():
  1087. -1 only lower
  1088. +1 only upper
  1089. 0 mixed
  1090. */
  1091. int word_state(const char *buffer, int len) {
  1092. int p;
  1093. int upper = 0;
  1094. int lower = 0;
  1095. int ret;
  1096. float pct;
  1097. for (p = 0; p < len; p++) {
  1098. char c = buffer[p];
  1099. if (isalpha(c)) {
  1100. if (isupper(c)) {
  1101. upper++;
  1102. };
  1103. if (islower(c)) {
  1104. lower++;
  1105. };
  1106. }
  1107. }
  1108. if (upper == lower) {
  1109. return 0;
  1110. }
  1111. if (upper > lower) {
  1112. ret = 1;
  1113. pct = ((float)lower / (float)upper) * 100.0;
  1114. } else {
  1115. ret = -1;
  1116. pct = ((float)upper / (float)lower) * 100.0;
  1117. }
  1118. // ZF_LOGD("So far %d with %f %%", ret, pct);
  1119. if (pct < 40.0) {
  1120. return ret;
  1121. }
  1122. return 0;
  1123. }
  1124. /*
  1125. Given a buffer and length, mangle away.
  1126. We *REALLY* want this to do something, so better run some tests.
  1127. Or, maybe we don't. This treats words consistently the same way.
  1128. HMM.
  1129. toupper, tolower, flipper
  1130. */
  1131. int word_mangler(char *buffer, int len) {
  1132. int p;
  1133. int count = 0;
  1134. int state;
  1135. state = word_state(buffer, len);
  1136. // ZF_LOGD("word_state(%.*s) %d", len, buffer, state);
  1137. // TODO: Transposer
  1138. for (p = 0; p < len; p++) {
  1139. char c = buffer[p];
  1140. switch (state) {
  1141. case -1:
  1142. // upper
  1143. if (islower(c)) {
  1144. count++;
  1145. buffer[p] = toupper(c);
  1146. }
  1147. break;
  1148. case 1:
  1149. // lower
  1150. if (isupper(c)) {
  1151. count++;
  1152. buffer[p] = tolower(c);
  1153. }
  1154. break;
  1155. case 0:
  1156. // flipper
  1157. if (islower(c)) {
  1158. count++;
  1159. buffer[p] = toupper(c);
  1160. } else {
  1161. if (isupper(c)) {
  1162. count++;
  1163. buffer[p] = tolower(c);
  1164. }
  1165. }
  1166. break;
  1167. }
  1168. }
  1169. return count;
  1170. }
  1171. /*
  1172. * The buffer that we've been given is much larger now.
  1173. *
  1174. */
  1175. int mangle(int fd, char *buffer) {
  1176. int x, i;
  1177. int need_render = 0; // changing word case around doesn't need the render
  1178. int mangled = 0;
  1179. int mangled_chars = 0;
  1180. char *cp;
  1181. // Ok, we want to look for words to:
  1182. // MaNGlE , or transpose (both?!)
  1183. // or possibly transpose words
  1184. char work[(BSIZE * 4) + 1];
  1185. // Use terminal - clean out ANSI
  1186. ZF_LOGI("mangle:");
  1187. ZF_LOGI_REPR(buffer);
  1188. ZF_LOGI("mangle(%s)", repr(buffer));
  1189. // strcpy(work, buffer);
  1190. /*
  1191. NOTE: We copy the buffer, so we can clear out ANSI codes, etc.
  1192. Otherwise we might mess some ANSI up in the manglying
  1193. process.
  1194. */
  1195. /*
  1196. (random) Look for ANSI CLS and:
  1197. display random spooky texts around, with delays ... then CLS.
  1198. display ANSI graphic file, with delays ... then CLS
  1199. */
  1200. const char *ANSI_CLS = "\x1b[2J";
  1201. static int ANSI_CLS_count = 0; // count the number we've seen
  1202. cp = strstr(buffer, ANSI_CLS);
  1203. if (cp != NULL) {
  1204. ZF_LOGI("seen: ANSI_CLS");
  1205. ANSI_CLS_count++;
  1206. // Don't activate on the very first CLS. Too soon, don't screw up the ANSI
  1207. // detection.
  1208. if (ANSI_CLS_count > 1) {
  1209. // Ok, figure out the restore color, just in case
  1210. struct console_details temp_console;
  1211. // Make exact copy of our current console state.
  1212. memcpy(&temp_console, &console, sizeof(console));
  1213. // Play the buffer into the console
  1214. console_receive(&temp_console, buffer, cp - buffer);
  1215. char restore_color[30]; // ansi color
  1216. strcpy(restore_color, color_restore(&temp_console));
  1217. if (random_activate(3)) {
  1218. char display[100] = "";
  1219. int needs_cls = 0;
  1220. struct file_need {
  1221. const char *filename;
  1222. int cls;
  1223. } possibles[] = {
  1224. {"goofy_head", 1},
  1225. {
  1226. "bat",
  1227. 1,
  1228. },
  1229. {"panther", 1},
  1230. {"wolf", 1}
  1231. // bat.ans creature.ans goofy_head.ans panther.ans
  1232. // skull.ans
  1233. // blinkman.ans dog.ans guy.ans skull2.ans wolf.ans
  1234. };
  1235. static LastSeen last_files(2);
  1236. int r;
  1237. do {
  1238. r = randint((sizeof(possibles) / sizeof(file_need)));
  1239. } while (last_files.seen_before(r));
  1240. // (2); // (sizeof(possibles) / sizeof(file_need)) - 1);
  1241. needs_cls = possibles[r].cls;
  1242. // I get what's happening. Mystic moves cursor to home, CLS, cursor
  1243. // home. When we get here, we're ALWAYS at the top of the screen...
  1244. // Hence our bat isn't displayed at the end of the screen.
  1245. // This is before the actual CLS, so we CLS before displaying our files.
  1246. // I tried a ^P2 before doing this .. but I'd rather have the picture up
  1247. // right away I think.
  1248. sprintf(display, "%s^F%s.^P3%s", needs_cls ? "\x1b[2J" : "\n\r\n\r",
  1249. possibles[r].filename, restore_color);
  1250. ZF_LOGI("mangle(ANSI_CLS): %d file inserted %s", r, display);
  1251. // Move the buffer so there's room for the display string.
  1252. if (string_insert(buffer, BSIZE * 4, cp - buffer, display)) {
  1253. ZF_LOGI("mangle(ANSI_CLS):");
  1254. ZF_LOGI_REPR(buffer);
  1255. ZF_LOGI("mangle(ANSI_CLS): [%s]", repr(buffer));
  1256. need_render = 1;
  1257. /*
  1258. Copy the new buffer over, but hide our "render" code
  1259. from the remaining mangler steps.
  1260. */
  1261. strcpy(work, buffer);
  1262. i = cp - buffer;
  1263. // find offset into "buffer"
  1264. // apply to work.
  1265. memset(work + i, ' ', strlen(display));
  1266. } else {
  1267. ZF_LOGD("insert failed [%s].", repr(display));
  1268. }
  1269. } else {
  1270. if (random_activate(4)) {
  1271. int r;
  1272. char display[100] = "";
  1273. const char *phrasing[] = {"^R1Haha^P1ha^P1ha", "Poof!", "Got U",
  1274. "Anyone there?", "^R1Knock, ^P1Knock"};
  1275. static LastSeen last_phrasing(2);
  1276. ZF_LOGI("mangle(ANSI_CLS)");
  1277. // sprintf( display, "^P2...");
  1278. // This string actually screws up ANSI detection (takes too long)
  1279. // strcpy(display, "^P2^S501234567890^P1abcdef^P2g^P3h^P4i^S0^P2");
  1280. // strcpy(display, "^P2^S301234^P15^S0^P2");
  1281. // Add in random text, plus color!
  1282. do {
  1283. r = random() % ((sizeof(phrasing) / sizeof(char *)) - 1);
  1284. } while (last_phrasing.seen_before(r));
  1285. int color = random() % 15 + 1;
  1286. int x = random() % 30 + 1;
  1287. int y = random() % 15 + 1;
  1288. /*
  1289. Don't have it pause there before moving the cursor.
  1290. Move the cursor, get the color changed, THEN pause.
  1291. Then act all crazy.
  1292. NOTE: Make sure if you use any ^R Render effects, turn them off
  1293. before trying to display the restore_color. :P ^R0 Also, make
  1294. sure you re-home the cursor ^G0101 because that's where they are
  1295. expecting the cursor to be! (At least it's how Mystic does it.)
  1296. HOME, CLS, HOME, ... Not sure what others do there. We'll see.
  1297. */
  1298. sprintf(display, "^G%02d%02d^S3^C%02d^P1%s^S0^R0%s^P1^G0101", x, y,
  1299. color, phrasing[r], restore_color);
  1300. // sprintf(display, "^P1^S3^C%02d%s^S0^R0%s^P1", color, phrasing[r],
  1301. // restore_color);
  1302. ZF_LOGI("mangle(ANSI_CLS): Inserted (%02d) %s", color, phrasing[r]);
  1303. // Move the buffer so there's room for the display string.
  1304. if (string_insert(buffer, BSIZE * 4, cp - buffer, display)) {
  1305. ZF_LOGI("mangle(ANSI_CLS):");
  1306. ZF_LOGI_REPR(buffer);
  1307. ZF_LOGI("mangle(ANSI_CLS): [%s]", repr(buffer));
  1308. need_render = 1;
  1309. /*
  1310. Copy the new buffer over, but hide our "render" code
  1311. from the remaining mangler steps.
  1312. */
  1313. strcpy(work, buffer);
  1314. i = cp - buffer;
  1315. // find offset into "buffer"
  1316. // apply to work.
  1317. memset(work + i, ' ', strlen(display));
  1318. } else {
  1319. ZF_LOGD("insert failed [%s].", repr(display));
  1320. }
  1321. }
  1322. }
  1323. }
  1324. }
  1325. strcpy(work, buffer); // sure.
  1326. const char replace_with = ' ';
  1327. for (x = 0; x < strlen(buffer); x++) {
  1328. int ansi = console_char(&console, buffer[x]);
  1329. if (ansi) {
  1330. work[x] = replace_with;
  1331. }
  1332. }
  1333. ZF_LOGD("work now:");
  1334. ZF_LOGD_REPR(work);
  1335. ZF_LOGD("Work Now: [%s]", repr(work));
  1336. #ifdef OLD_WAY
  1337. /* work -- clear out ANSI so we don't mangle ANSI codes. */
  1338. x = rx_match(&ANSI, work);
  1339. if (x > 0) {
  1340. ZF_LOGD("found %d ANSI", x);
  1341. for (i = 0; i < x; i++) {
  1342. memset(work + rxmatch[i].rm_so, replace_with,
  1343. rxmatch[i].rm_eo - rxmatch[i].rm_so);
  1344. };
  1345. ZF_LOGD("Work Now: [%s]", repr(work));
  1346. }
  1347. #endif
  1348. // ZF_LOGI("mangle: %s", repr(work));
  1349. /*
  1350. (random) Locate words (in work), and possibly flip them around.
  1351. Transpose words. Transpose case. Transpose letters.
  1352. */
  1353. x = rx_match(&WORDS, work);
  1354. ZF_LOGD("found %d word groups", x);
  1355. if (x > 0) {
  1356. for (i = 0; i < x; i++) {
  1357. // Yes! Be random!
  1358. if (random_activate(8)) {
  1359. int c = word_mangler(buffer + rxmatch[i].rm_so,
  1360. rxmatch[i].rm_eo - rxmatch[i].rm_so);
  1361. if (c) {
  1362. mangled++;
  1363. mangled_chars += c;
  1364. }
  1365. }
  1366. // Do things here.
  1367. /*
  1368. // NO! This is predictable
  1369. if (i % 3 == 0) {
  1370. mangled++;
  1371. for (int p = rxmatch[i].rm_so; p < rxmatch[i].rm_eo; p++) {
  1372. buffer[p] = tolower(buffer[p]);
  1373. mangled_chars++;
  1374. }
  1375. } else {
  1376. if (i % 3 == 1) {
  1377. mangled++;
  1378. for (int p = rxmatch[i].rm_so; p < rxmatch[i].rm_eo; p++) {
  1379. buffer[p] = toupper(buffer[p]);
  1380. mangled_chars++;
  1381. }
  1382. }
  1383. }
  1384. */
  1385. }
  1386. }
  1387. /*
  1388. (random) Locate single words, and transpose words.
  1389. Transpose letters.
  1390. */
  1391. /*
  1392. (random) Display up to certain point. Delay.
  1393. Print some characters slowly. Delay.
  1394. */
  1395. if (need_render) {
  1396. ZF_LOGD("HH %d : (%d) %s", need_render, (int)strlen(buffer), repr(buffer));
  1397. } else {
  1398. if (mangled) {
  1399. ZF_LOGD("Mangled %d words, %d chars : %s", mangled, mangled_chars,
  1400. repr(buffer));
  1401. }
  1402. }
  1403. if (need_render) {
  1404. render(fd, buffer);
  1405. } else {
  1406. write(fd, buffer, strlen(buffer));
  1407. };
  1408. return need_render && mangled;
  1409. }
  1410. int harry_happens(time_t *last_event, int wakeup) {
  1411. time_t now = time(NULL);
  1412. int elapsed = now - *last_event;
  1413. if (elapsed > wakeup) {
  1414. // Ok! It's been too long since we've done something.
  1415. *last_event = now;
  1416. return 1;
  1417. }
  1418. return 0;
  1419. }
  1420. int main(int argc, char *argv[]) {
  1421. int master;
  1422. pid_t pid;
  1423. int node = -1;
  1424. file_output_open("horrible_harry.log");
  1425. init_harry();
  1426. srandom(time(NULL));
  1427. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown
  1428. // -Ubugz -PUWISHPASSWORD
  1429. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  1430. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown
  1431. // -Ubugz -PUWISH
  1432. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  1433. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  1434. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML0 -SL1 -ST0 -CUnknown
  1435. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown
  1436. // -Ubugz -PDUMBWAYTODOTHIS
  1437. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML1 -SL1 -ST2 -CUnknown
  1438. // -Ubugz -PIDONTUSEPASCAL
  1439. // SSH: -ML1 -ST2
  1440. // Telnet: -ML0 -ST0
  1441. // Locate username (if given) in the command line
  1442. // -U<username>
  1443. for (int x = 0; x < argc; x++) {
  1444. if (strncmp("-U", argv[x], 2) == 0) {
  1445. username = argv[x] + 2;
  1446. ZF_LOGI("Username: [%s]", username);
  1447. };
  1448. if (strncmp("-SL", argv[x], 3) == 0) {
  1449. node = argv[x][3] - '0' + 1;
  1450. ZF_LOGI("Node: %d", node);
  1451. }
  1452. }
  1453. if (username != NULL) {
  1454. locate_user(username);
  1455. ZF_LOGD("Username: [%s] A.K.A. [%s]", username, fullname);
  1456. }
  1457. if (!init_regex())
  1458. return 2;
  1459. // With IGNBRK I don't think I need this anymore. (Nope!)
  1460. // signal(SIGINT, SIG_IGN);
  1461. pid = forkpty(&master, NULL, NULL, NULL);
  1462. // impossible to fork
  1463. if (pid < 0) {
  1464. return 1;
  1465. }
  1466. // child
  1467. else if (pid == 0) {
  1468. char *args[20]; // max 20 args
  1469. int x;
  1470. char new_exec[] = TARGET;
  1471. args[0] = new_exec;
  1472. for (x = 1; x < argc; x++) {
  1473. args[x] = argv[x];
  1474. };
  1475. args[x] = NULL;
  1476. // run Mystic, run!
  1477. execvp(TARGET, args);
  1478. }
  1479. // parent
  1480. else {
  1481. // remove the echo
  1482. // ICANON - raw mode. No more line buffering!
  1483. struct termios tios, orig1;
  1484. struct timeval timeout;
  1485. time_t last_event = 0; // time(NULL);
  1486. ZF_LOGD("starting");
  1487. tcgetattr(master, &tios);
  1488. tios.c_lflag &= ~(ECHO | ECHONL | ICANON);
  1489. tcsetattr(master, TCSAFLUSH, &tios);
  1490. tcgetattr(1, &orig1);
  1491. tios = orig1;
  1492. tios.c_iflag &= ~(ICRNL | IXON); // Disable software flow control
  1493. tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  1494. // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
  1495. // ISIG should be Ctrl-C and Ctrl-Z IGNBRK +
  1496. tcsetattr(1, TCSAFLUSH, &tios);
  1497. for (;;) {
  1498. // define estruturas para o select, que serve para verificar qual
  1499. // se tornou "pronto pra uso"
  1500. fd_set read_fd;
  1501. fd_set write_fd;
  1502. fd_set except_fd;
  1503. // inicializa as estruturas
  1504. FD_ZERO(&read_fd);
  1505. FD_ZERO(&write_fd);
  1506. FD_ZERO(&except_fd);
  1507. // atribui o descritor master, obtido pelo forkpty, ao read_fd
  1508. FD_SET(master, &read_fd);
  1509. // atribui o stdin ao read_fd
  1510. FD_SET(STDIN_FILENO, &read_fd);
  1511. // o descritor tem que ser unico para o programa, a documentacao
  1512. // recomenda um calculo entre os descritores sendo usados + 1
  1513. /*
  1514. TODO: Figure out how this would work.
  1515. I'm thinking something like timeouts 30-50 seconds?
  1516. And as we get closer, 15-25 seconds.
  1517. */
  1518. // we're in luck! The last parameter is time interval/timeout. :D
  1519. timeout.tv_sec = 10;
  1520. timeout.tv_usec = 0;
  1521. // select(master+1, &read_fd, &write_fd, &except_fd, NULL);
  1522. if (select(master + 1, &read_fd, &write_fd, &except_fd, &timeout) == 0) {
  1523. // This means timeout!
  1524. ZF_LOGI("TIMEOUT");
  1525. harry_idle_event(STDOUT_FILENO);
  1526. }
  1527. char input[BSIZE + 1];
  1528. static char output[(BSIZE * 4) + 1];
  1529. int total;
  1530. // read_fd esta atribuido com read_fd?
  1531. if (FD_ISSET(master, &read_fd)) {
  1532. // leia o que bc esta mandando
  1533. if ((total = read(master, &output, BSIZE)) != -1) {
  1534. // e escreva isso na saida padrao
  1535. output[total] = 0;
  1536. // if ( harry_happens( &last_event, 5)) {
  1537. if (1) {
  1538. ZF_LOGI("harry_happens");
  1539. if (mangle(STDOUT_FILENO, output) == 0) {
  1540. // failed, so. Try again.
  1541. last_event = 0;
  1542. }
  1543. } else {
  1544. write(STDOUT_FILENO, &output, total);
  1545. // This is OUTPUT from the BBS
  1546. // ZF_LOGI( ">> %s", repr(output));
  1547. ZF_LOGI(">> %d chars", (int)strlen(output));
  1548. // I think repr is flipping out here. :(
  1549. // ZF_LOGI( ">> %d", (int)strlen(repr(output)));
  1550. }
  1551. } else
  1552. break;
  1553. }
  1554. // read_fd esta atribuido com a entrada padrao?
  1555. if (FD_ISSET(STDIN_FILENO, &read_fd)) {
  1556. // leia a entrada padrao
  1557. total = read(STDIN_FILENO, &input, BSIZE);
  1558. input[total] = 0;
  1559. // e escreva no bc
  1560. ZF_LOGI("<< %s", repr(input));
  1561. write(master, &input, total);
  1562. // This is INPUT from the USER
  1563. // ZF_LOGI_MEM( input, strlen(input), "<< ");
  1564. }
  1565. }
  1566. // Restore terminal
  1567. tcsetattr(1, TCSAFLUSH, &orig1);
  1568. ZF_LOGD("exit");
  1569. }
  1570. return 0;
  1571. }