mystic.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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. // LOGGING with file output
  16. #include "zf_log.h"
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. FILE *g_log_file;
  20. static void file_output_callback(const zf_log_message *msg, void *arg) {
  21. (void)arg;
  22. *msg->p = '\n';
  23. fwrite(msg->buf, msg->p - msg->buf + 1, 1, g_log_file);
  24. fflush(g_log_file);
  25. }
  26. static void file_output_close(void) { fclose(g_log_file); }
  27. static void file_output_open(const char *const log_path) {
  28. g_log_file = fopen(log_path, "a");
  29. if (!g_log_file) {
  30. ZF_LOGW("Failed to open log file %s", log_path);
  31. return;
  32. }
  33. atexit(file_output_close);
  34. zf_log_set_output_v(ZF_LOG_PUT_STD, 0, file_output_callback);
  35. }
  36. // END LOGGING
  37. /*
  38. What is the name of the actual, real Mystic executable
  39. that we'll be executing and mangling?
  40. */
  41. #define TARGET "./mySTIC"
  42. // Size of our input and output buffers.
  43. #define BSIZE 128
  44. /*
  45. // Don't need this, zf_log does date/time stamps on output.
  46. const char * it_is_now(void) {
  47. static char buffer[100];
  48. time_t timer;
  49. struct tm* tm_info;
  50. timer = time(NULL);
  51. tm_info = localtime(&timer);
  52. strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", tm_info);
  53. return buffer;
  54. }
  55. void slow_write(int fd, int speed, char * buffer, int len) {
  56. int x;
  57. for( x = 0; x < len; x++) {
  58. usleep(speed);
  59. write( fd, &buffer[x], 1);
  60. }
  61. }
  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. struct render {
  135. int speed;
  136. int effect;
  137. } current_render;
  138. int render_overlimit = 0;
  139. void reset_render(void) {
  140. current_render.speed = 0;
  141. current_render.effect = 0;
  142. render_overlimit = 0;
  143. }
  144. #define TRIGGER "^"
  145. // Max limit we'll sleep before ignoring effects/speed.
  146. #define SLEEP_LIMIT 30
  147. int ms_sleep(unsigned int ms) {
  148. int result = 0;
  149. struct timespec ts = {ms / 1000, (ms % 1000) * 1000000L};
  150. do {
  151. struct timespec ts_sleep = ts;
  152. result = nanosleep(&ts_sleep, &ts);
  153. } while ((-1 == result));
  154. return result;
  155. }
  156. void render_sleep(void) {
  157. if (render_overlimit)
  158. return;
  159. if (current_render.speed) { // * 100 still too slow.
  160. ms_sleep(current_render.speed * 10);
  161. }
  162. }
  163. /*
  164. Terminal tracking
  165. */
  166. struct console_details {
  167. int posx, posy;
  168. int savedx, savedy;
  169. char ansi[20]; // current ANSI command being processed.
  170. int in_ansi;
  171. int fgcolor; // 0-15
  172. int bgcolor; // 0-7
  173. int status; // 0 or 5 (Blink)
  174. } console;
  175. void console_init(struct console_details *cdp) {
  176. cdp->posx = 0;
  177. cdp->posy = 0;
  178. cdp->savedx = 0;
  179. cdp->savedy = 0;
  180. cdp->in_ansi = 0;
  181. cdp->fgcolor = 0;
  182. cdp->bgcolor = 0;
  183. cdp->status = 0;
  184. }
  185. void console_ansi(const char *ansi) {
  186. int understood = 0;
  187. const char *cp = ansi;
  188. const char *last = ansi + strlen(ansi) - 1;
  189. int number, number2;
  190. if (*cp == '\x1b') {
  191. cp++;
  192. // Ok, that's expected.
  193. if (*cp == '[') {
  194. cp++;
  195. // https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_sequences
  196. switch (*last) {
  197. case 'A':
  198. // cursor up
  199. if (cp == last) {
  200. number = 1;
  201. } else {
  202. number = atoi(cp);
  203. if (number < 1) {
  204. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi), number);
  205. number = 1;
  206. }
  207. };
  208. console.posy -= number;
  209. if (console.posy < 0) {
  210. console.posy = 0;
  211. ZF_LOGD("console_ansi( %s ): attempt to move above top of screen (%d)", repr(ansi), number);
  212. }
  213. understood = 1;
  214. return;
  215. case 'B':
  216. // cursor down
  217. if (cp == last) {
  218. number = 1;
  219. } else {
  220. number = atoi(cp);
  221. if (number < 1) {
  222. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi), number);
  223. number = 1;
  224. }
  225. };
  226. console.posy += number;
  227. // check range/"scroll"
  228. understood = 1;
  229. return;
  230. case 'C':
  231. // cursor forward
  232. if (cp == last) {
  233. number = 1;
  234. } else {
  235. number = atoi(cp);
  236. if (number < 1) {
  237. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi), number);
  238. number = 1;
  239. }
  240. };
  241. console.posx += number;
  242. // Well. According to the "spec", the screen limits are hard
  243. // If the cursor is already at the edge of the screen, this has no effect.
  244. // ^ This is *NOT* how any ANSI BBS terminal program acts!
  245. while (console.posx > 79) {
  246. console.posy++;
  247. // check range/"scroll"
  248. console.posx -= 79;
  249. }
  250. understood = 1;
  251. return;
  252. case 'D':
  253. // cursor backwards
  254. if (cp == last) {
  255. number = 1;
  256. } else {
  257. number = atoi(cp);
  258. if (number < 1) {
  259. ZF_LOGD("console_ansi( %s ): number error (%d)", repr(ansi), number);
  260. number = 1;
  261. }
  262. };
  263. console.posx -= number;
  264. // Well. According to the "spec", the screen limits are hard
  265. // If the cursor is already at the edge of the screen, this has no effect.
  266. // ^ This is *NOT* how any ANSI BBS terminal program acts!
  267. while (console.posx < 0) {
  268. console.posy--;
  269. if (console.posy < 0 ) {
  270. console.posy = 0;
  271. }
  272. console.posx += 79;
  273. }
  274. understood = 1;
  275. return;
  276. case 'H':
  277. // cursor position
  278. if (*cp == ';') {
  279. // Missing first number
  280. number = 1;
  281. cp++;
  282. if (cp == last) {
  283. // missing 2nd number as well?
  284. number2 = 1;
  285. } else {
  286. number2 = atoi(cp);
  287. }
  288. } else {
  289. // Ok, find the first number
  290. number = atoi(cp);
  291. cp = strchr(cp, ';');
  292. if ( cp == NULL) {
  293. // Missing 2nd number
  294. number2 = 1;
  295. } else {
  296. // 2nd number found, maybe.
  297. cp++;
  298. if (cp == last) {
  299. number2 = 1;
  300. } else {
  301. number2 = atoi(cp);
  302. }
  303. }
  304. }
  305. // Our positions start at zero, not one.
  306. console.posx = number - 1;
  307. console.posy = number2 - 1;
  308. understood = 1;
  309. break;
  310. case 'J':
  311. // clear
  312. if (cp == last) {
  313. number = 0;
  314. } else {
  315. number = atoi(cp);
  316. };
  317. // clears ... part of the screen.
  318. if (number == 2 ) {
  319. console.posx = 0;
  320. console.posy = 0;
  321. };
  322. understood = 1;
  323. break;
  324. default:
  325. // unsure -- possibly not important
  326. ZF_LOGD("console_ansi( %s ): ???", repr(ansi));
  327. understood = 0;
  328. }
  329. }
  330. };
  331. if (!understood) {
  332. ZF_LOGD("console_ansi( %s ): was not understood.", repr(ansi));
  333. }
  334. }
  335. void console_char(char ch) {
  336. char *cp;
  337. if (console.in_ansi) {
  338. // Ok, append this char
  339. cp = console.ansi + strlen(console.ansi);
  340. *cp = ch;
  341. cp++;
  342. *cp = 0;
  343. if (isalpha(ch)) {
  344. // Ok!
  345. console_ansi(console.ansi);
  346. console.in_ansi = 0;
  347. console.ansi[0] = 0;
  348. return;
  349. }
  350. } else {
  351. if (ch == '\x1b') {
  352. cp = console.ansi;
  353. *cp = ch;
  354. cp++;
  355. *cp = 0;
  356. console.in_ansi = 1;
  357. return;
  358. }
  359. if (ch == '\r') {
  360. // Carriage return
  361. console.posx = 0;
  362. return;
  363. }
  364. if (ch == '\n') {
  365. console.posy++;
  366. // check range/"scroll"
  367. return;
  368. }
  369. if (ch == '\b') {
  370. // Backspace.
  371. if (console.posx > 0) {
  372. console.posx--;
  373. }
  374. return;
  375. }
  376. if (ch == '\f') {
  377. // form feed
  378. // treat as clear screen
  379. console.posx = 0;
  380. console.posy = 0;
  381. return;
  382. }
  383. /*
  384. I don't believe that anything else can possibly be here, other then an
  385. actual printable character. So!
  386. */
  387. console.posx++;
  388. if (console.posx > 79) {
  389. console.posx = 0;
  390. console.posy++;
  391. // check range/"scroll"
  392. }
  393. }
  394. }
  395. void console_string(const char *chars) {
  396. int x;
  397. for (x = 0; x < strlen(chars); x++) {
  398. console_char(chars[x]);
  399. }
  400. }
  401. void console_receive(const char *chars, int len) {
  402. int x;
  403. for (x = 0; x < len; x++) {
  404. console_char(chars[x]);
  405. }
  406. }
  407. /*
  408. Well SNAP! Mystic numbers don't remotely match ANSI color codes.
  409. 00 : Sets the current foreground to Black 0;30
  410. 01 : Sets the current foreground to Dark Blue 0;34
  411. 02 : Sets the current foreground to Dark Green 0;32
  412. 03 : Sets the current foreground to Dark Cyan 0;36
  413. 04 : Sets the current foreground to Dark Red 0;31
  414. 05 : Sets the current foreground to Dark Magenta 0;35
  415. 06 : Sets the current foreground to Brown 0;33
  416. 07 : Sets the current foreground to Grey 0;37
  417. 08 : Sets the current foreground to Dark Grey 1;30
  418. 09 : Sets the current foreground to Light Blue 1;34
  419. 10 : Sets the current foreground to Light Green 1;32
  420. 11 : Sets the current foreground to Light Cyan 1;36
  421. 12 : Sets the current foreground to Light Red 1;31
  422. 13 : Sets the current foreground to Light Magenta 1;35
  423. 14 : Sets the current foreground to Yellow 1;33
  424. 15 : Sets the current foreground to White 1;37
  425. 16 : Sets the current background to Black 40
  426. 17 : Sets the current background to Blue 44
  427. 18 : Sets the current background to Green 42
  428. 19 : Sets the current background to Cyan 46
  429. 20 : Sets the current background to Red 41
  430. 21 : Sets the current background to Magenta 45
  431. 22 : Sets the current background to Brown 43
  432. 23 : Sets the current background to Grey 47
  433. 24 : Sets the current background to black with blinking foreground 5;40
  434. 25 : Sets the current background to blue with blinking foreground 5;44
  435. 26 : Sets the current background to green with blinking foreground 5;42
  436. 27 : Sets the current background to cyan with blinking foreground 5;46
  437. 28 : Sets the current background to red with blinking foreground 5;41
  438. 29 : Sets the current background to magenta with blinking foreground 5;45
  439. 30 : Sets the current background to brown with blinking foreground 5;43
  440. 31 : Sets the current background to grey with blinking foreground 5;47
  441. Other things that Mystic does ...
  442. [A## - Move the cursor up ## lines
  443. [B## - Move the cursor down ## lines
  444. [C## - Move the cursor forward (to the right) ## columns
  445. [D## - Move the cursor backwards (to the left) ## columns
  446. [K - Clear from the current cursor position to the end of the line
  447. [L - Move cursor and erase data backwards from current column to column ##
  448. [X## - Move cursor to X coordinate ##
  449. [Y## - Move cursor to Y coordinate ##
  450. BS - Sends 1 destructive backspace sequence (ASCII 8-32-8)
  451. CL - Clears the screen (ANSI 1,1 locate and [2J or ASCII 12)
  452. CR - Send a carrage return and line feed (move to next line)
  453. RA - Restore the saved text attribute color
  454. RS - Restore the saved user's terminal screen
  455. SA - Save the current text attribute color
  456. SS - Save the entire user's terminal screen
  457. */
  458. // Covert MYSTIC color to (Proper) ANSI COLOR.
  459. const int MYSTIC[] = {0, 4, 2, 6, 1, 5, 3, 7};
  460. // ANSI_color = MYSTIC[ odd_mystic_color % 8 ]
  461. void write_color(int fd, int color) {
  462. char buffer[10];
  463. switch (color) {
  464. case 0:
  465. case 1:
  466. case 2:
  467. case 3:
  468. case 4:
  469. case 5:
  470. case 6:
  471. case 7:
  472. sprintf(buffer, "\x1b[0;3%dm", MYSTIC[color]);
  473. break;
  474. case 8:
  475. case 9:
  476. case 10:
  477. case 11:
  478. case 12:
  479. case 13:
  480. case 14:
  481. case 15:
  482. sprintf(buffer, "\x1b[1;3%dm", MYSTIC[color - 8]);
  483. break;
  484. case 16:
  485. case 17:
  486. case 18:
  487. case 19:
  488. case 20:
  489. case 21:
  490. case 22:
  491. case 23:
  492. sprintf(buffer, "\x1b[4%dm", MYSTIC[color - 16]);
  493. break;
  494. case 24:
  495. case 25:
  496. case 26:
  497. case 27:
  498. case 28:
  499. case 29:
  500. case 30:
  501. case 31:
  502. sprintf(buffer, "\x1b[5;4%dm", MYSTIC[color - 24]);
  503. break;
  504. default:
  505. buffer[0] = 0;
  506. break;
  507. }
  508. ZF_LOGD("write_color( %d ): %s", color, repr(buffer));
  509. write(fd, buffer, strlen(buffer));
  510. }
  511. /**
  512. * process_trigger( fd, *cp )
  513. *
  514. * This process a command trigger.
  515. * It has seen TRIGGER, and now it is
  516. * processing whatever comes after it.
  517. * It will perform the process, and
  518. * return the char * of whatever is next.
  519. */
  520. const char *process_trigger(int fd, const char *cp) {
  521. char ch;
  522. int i, x, y;
  523. ch = toupper(*cp);
  524. cp++;
  525. switch (ch) {
  526. case 'D':
  527. i = 0;
  528. if (isdigit(*cp)) {
  529. i = (*cp) - '0';
  530. cp++;
  531. };
  532. if (isdigit(*cp)) {
  533. i *= 10;
  534. i += (*cp) - '0';
  535. cp++;
  536. };
  537. if ((i > 0) && (i < 80)) {
  538. ZF_LOGI("DEL %02d", i);
  539. for (x = 0; x < i; x++) {
  540. write(fd, "\b \b", 3);
  541. }
  542. };
  543. break;
  544. case 'C':
  545. i = 0;
  546. if (isdigit(*cp)) {
  547. i = (*cp) - '0';
  548. cp++;
  549. };
  550. if (isdigit(*cp)) {
  551. i *= 10;
  552. i += (*cp) - '0';
  553. cp++;
  554. };
  555. write_color(fd, i);
  556. break;
  557. case 'G':
  558. x = 0;
  559. if (isdigit(*cp)) {
  560. x = (*cp) - '0';
  561. cp++;
  562. };
  563. if (isdigit(*cp)) {
  564. x *= 10;
  565. x += (*cp) - '0';
  566. cp++;
  567. };
  568. y = 0;
  569. if (isdigit(*cp)) {
  570. y = (*cp) - '0';
  571. cp++;
  572. };
  573. if (isdigit(*cp)) {
  574. y *= 10;
  575. y += (*cp) - '0';
  576. cp++;
  577. };
  578. break;
  579. case 'R':
  580. i = 0;
  581. if (isdigit(*cp)) {
  582. i = (*cp) - '0';
  583. cp++;
  584. };
  585. if ((i > 0) && (i < 10)) {
  586. ZF_LOGI("RENDER %d", i);
  587. current_render.effect = i;
  588. } else {
  589. current_render.effect = 0;
  590. }
  591. break;
  592. case 'S':
  593. i = 0;
  594. if (isdigit(*cp)) {
  595. i = (*cp) - '0';
  596. cp++;
  597. };
  598. if ((i > 0) && (i < 10)) {
  599. ZF_LOGI("SPEED %d", i);
  600. current_render.speed = i;
  601. } else {
  602. current_render.speed = 0;
  603. }
  604. break;
  605. case 'P':
  606. i = 0;
  607. if (isdigit(*cp)) {
  608. i = (*cp) - '0';
  609. cp++;
  610. };
  611. if ((i > 0) && (i < 10)) {
  612. ZF_LOGI("PAWS %d", i);
  613. // sleep(i);
  614. if (!render_overlimit) {
  615. sleep(i);
  616. };
  617. }
  618. break;
  619. }
  620. return cp;
  621. }
  622. /**
  623. * render_effect( fd, ch )
  624. *
  625. * Displays the given character with whatever
  626. * rendering effect is currently active.
  627. * (If any).
  628. */
  629. void render_effect(int fd, char ch) {
  630. int effect = current_render.effect;
  631. int l;
  632. char space = ' ';
  633. char bs = '\b';
  634. switch (effect) {
  635. case 1:
  636. // CHAR + SPC + BS
  637. render_sleep();
  638. write(fd, &ch, 1);
  639. render_sleep();
  640. write(fd, &space, 1);
  641. render_sleep();
  642. render_sleep();
  643. write(fd, &bs, 1);
  644. break;
  645. case 2:
  646. // CHAR + 8 spaces + 8 BS
  647. render_sleep();
  648. write(fd, &ch, 1);
  649. for (l = 0; l < 8; l++) {
  650. render_sleep();
  651. write(fd, &space, 1);
  652. }
  653. for (l = 0; l < 8; l++) {
  654. render_sleep();
  655. write(fd, &bs, 1);
  656. }
  657. break;
  658. case 0:
  659. default:
  660. // NORMAL
  661. render_sleep();
  662. write(fd, &ch, 1);
  663. break;
  664. }
  665. }
  666. /**
  667. * render( fd, string_out )
  668. *
  669. * Render an entire string.
  670. * Handles TRIGGER.
  671. * Renders with effects.
  672. */
  673. void render(int fd, const char *string_out) {
  674. const char *cp = string_out;
  675. const char *trigger = cp;
  676. time_t start = time(NULL);
  677. int elapsed;
  678. int over = 0;
  679. reset_render();
  680. ZF_LOGD("render(%d, %s)", fd, repr(string_out));
  681. // Check our time from time to time.
  682. // If we start running long, disable sleeps.
  683. while ((trigger = strstr(cp, TRIGGER)) != NULL) {
  684. // There is special things to handle in here.
  685. while (cp != trigger) {
  686. elapsed = time(NULL) - start;
  687. if (elapsed > SLEEP_LIMIT) {
  688. render_overlimit = 1;
  689. current_render.speed = 0;
  690. };
  691. // write(fd, cp, 1 );
  692. render_effect(fd, *cp);
  693. cp++;
  694. };
  695. // ZF_LOGI( "at trigger: (%s)", cp);
  696. cp += strlen(TRIGGER);
  697. // Ok, we're pointing at the trigger -- do something.
  698. cp = process_trigger(fd, cp);
  699. // ZF_LOGI( "after trigger: (%s)", cp);
  700. };
  701. // We still might be under a rendering effect.
  702. while (*cp != 0) {
  703. elapsed = time(NULL) - start;
  704. if (elapsed > SLEEP_LIMIT) {
  705. render_overlimit = 1;
  706. current_render.speed = 0;
  707. };
  708. // write(fd, cp, 1);
  709. render_effect(fd, *cp);
  710. cp++;
  711. }
  712. }
  713. // Beanzilla's no repeats
  714. /**
  715. * have_seen( list, len, item )
  716. *
  717. * Returns 1 (true) if item is in the list.
  718. * Rotates the list [x] = [x+1], and
  719. * list[len-1] = item, return 0 (false)
  720. */
  721. int have_seen(int *list, int len, int item) {
  722. int x;
  723. for (x = 0; x < len; x++) {
  724. if (list[x] == item) {
  725. return 1;
  726. }
  727. };
  728. // Ok, it is something different
  729. for (x = 0; x < len - 1; x++) {
  730. list[x] = list[x + 1];
  731. };
  732. list[x] = item;
  733. return 0;
  734. }
  735. /**
  736. * init_have_seen( list, len )
  737. *
  738. * Initialize the have_seen list with -1.
  739. * (-1 isn't a valid index, so we start
  740. * out with all invalid.)
  741. */
  742. void init_have_seen(int *list, int len) {
  743. int x;
  744. for (x = 0; x < len; x++) {
  745. list[x] = -1;
  746. }
  747. }
  748. /*
  749. These are harry "timeout" events.
  750. These happen when we've been sitting around awhile.
  751. */
  752. #define MAX_HARRY_EVENT_DUPS 2
  753. int last_seen_harry_event[MAX_HARRY_EVENT_DUPS];
  754. #ifdef CPP_MADMAN_STL_CODE
  755. const char *random_phrase(const char *words, int len, int last_seen) {
  756. // ooh. a map of char *s to last_seen_events. :P
  757. static map<const char *, array<int>> tracker;
  758. map<const char *, array<int>>::iterator it;
  759. array<int, last_seen> it = tracker.find(words);
  760. if (it == tracker.end()) {
  761. // key does not exist.
  762. array<int, last_seen> last;
  763. for (int i = 0; i < last_seen; i++) {
  764. last[i] = -1;
  765. };
  766. tracker.insert(words, last);
  767. it = tracker.find(words);
  768. };
  769. }
  770. #endif
  771. void harry_event(int fd) {
  772. // Make something happen
  773. char buffer[100];
  774. int r;
  775. // This is no where near finished, BUT!
  776. const char *phrases[] = {"Hahaha", "Snicker, snicker", "Boo!",
  777. "MeOW", "I see U", "Arrooo!",
  778. "Ahh-wooo!", "Aaaooo!"};
  779. const char *cp;
  780. // Remember the last phrase used,
  781. // and don't repeat (the last two)!
  782. do {
  783. r = random() % ((sizeof(phrases) / sizeof(char *)) - 1);
  784. } while (have_seen(last_seen_harry_event, MAX_HARRY_EVENT_DUPS, r));
  785. ZF_LOGD("%d => %d %d", r, last_seen_harry_event[0], last_seen_harry_event[1]);
  786. cp = phrases[r];
  787. int color = random() % 16;
  788. if(color == 0){ color++; } // If it's 0 let's make it 1.
  789. sprintf(buffer, "^S2^C%02d%s^P2^D%02d", color, cp, (int)strlen(cp));
  790. ZF_LOGD("harry_event: render(%d, \"%s\")", fd, buffer);
  791. render(fd, buffer);
  792. }
  793. void init_harry() {
  794. init_have_seen(last_seen_harry_event, MAX_HARRY_EVENT_DUPS);
  795. ZF_LOGD("init => %d %d", last_seen_harry_event[0], last_seen_harry_event[1]);
  796. }
  797. /*
  798. The code to get the username and fullname is useless on telnet
  799. connections.
  800. */
  801. char *username = NULL;
  802. char *fullname = NULL;
  803. /*
  804. Pascal String Copy. Copy from pascal string, to C String.
  805. First char is pascal string length. (Max 255).
  806. */
  807. void pcopy(char *pstring, char *str) {
  808. int len = (int)*pstring;
  809. strncpy(str, pstring + 1, len);
  810. str[len] = 0;
  811. }
  812. /*
  813. This only works for those few idiots that use the
  814. horribly broken SSH crap that Mystic uses.
  815. */
  816. int locate_user(const char *alias) {
  817. FILE *user;
  818. char buffer[0x600];
  819. char temp[100];
  820. user = fopen("data/users.dat", "rb");
  821. if (user == NULL)
  822. return 0;
  823. // Carry on!
  824. while (fread(buffer, 0x600, 1, user) == 1) {
  825. pcopy(buffer + 0x6d, temp);
  826. if (strcasecmp(temp, username) == 0) {
  827. pcopy(buffer + 0x8c, temp);
  828. fullname = strdup(temp);
  829. break;
  830. }
  831. /*
  832. printf("Alias: %s\n", temp);
  833. pcopy(buffer + 0x8c, temp );
  834. printf("Full Name: %s\n", temp );
  835. */
  836. }
  837. fclose(user);
  838. return 1;
  839. }
  840. // Buffers are BSIZE + 1, so a buffer that size can strcpy safely.
  841. regex_t ANSI;
  842. regex_t WORDS;
  843. regex_t WORD;
  844. int init_regex(void) {
  845. int ret;
  846. char ansi[] = "\x1b\[[0-9]+(;[0-9]+)*?[a-zA-Z]";
  847. char words[] = "[a-zA-Z]+( [a-zA-Z]+)+";
  848. char word[] = "[a-zA-Z]+";
  849. char errorbuf[100];
  850. if (ret = regcomp(&ANSI, ansi, REG_EXTENDED | REG_NEWLINE)) {
  851. regerror(ret, &ANSI, errorbuf, sizeof(errorbuf));
  852. ZF_LOGW("Regex %s failed to compile: %s", ansi, errorbuf);
  853. return 0;
  854. };
  855. if (ret = regcomp(&WORDS, words, REG_EXTENDED | REG_NEWLINE)) {
  856. regerror(ret, &WORDS, errorbuf, sizeof(errorbuf));
  857. ZF_LOGW("Regex %s failed to compile: %s", words, errorbuf);
  858. return 0;
  859. };
  860. if (ret = regcomp(&WORD, word, REG_EXTENDED | REG_NEWLINE)) {
  861. regerror(ret, &WORD, errorbuf, sizeof(errorbuf));
  862. ZF_LOGW("Regex %s failed to compile: %s", word, errorbuf);
  863. return 0;
  864. };
  865. return 1;
  866. }
  867. int regmatch(regex_t *preg, const char *string, size_t nmatch,
  868. regmatch_t pmatch[], int eflags) {
  869. // returns number of matches found. (Max nmatch)
  870. int matches = 0;
  871. int offset = 0;
  872. int ret;
  873. while (matches < nmatch) {
  874. ret = regexec(preg, string + offset, nmatch - matches, pmatch + matches,
  875. eflags);
  876. if (!ret) {
  877. int current = offset;
  878. offset += pmatch[matches].rm_eo;
  879. pmatch[matches].rm_so += current;
  880. pmatch[matches].rm_eo += current;
  881. matches++;
  882. } else if (ret == REG_NOMATCH) {
  883. break;
  884. } else {
  885. break;
  886. }
  887. }
  888. return matches;
  889. }
  890. #define MAX_MATCH 32
  891. regmatch_t rxmatch[MAX_MATCH];
  892. int rx_match(regex_t *regex, const char *buffer) {
  893. int ret;
  894. ret = regmatch(regex, buffer, MAX_MATCH, rxmatch, 0);
  895. if (0) {
  896. for (int i = 0; i < ret; i++) {
  897. ZF_LOGI("%d : (%d-%d)", i, rxmatch[i].rm_so, rxmatch[i].rm_eo);
  898. }
  899. }
  900. return ret;
  901. }
  902. /*
  903. Terminal processing section.
  904. Monitor lines, position, color.
  905. What screen size do I want to emulate?
  906. ANSI codes.
  907. Do I need this??
  908. */
  909. int random_activate(int w) {
  910. int r = random() % 100;
  911. if (r <= (w * 10)) {
  912. return 1;
  913. };
  914. return 0;
  915. }
  916. /*
  917. * The buffer that we've been given is much larger now.
  918. *
  919. */
  920. int mangle(int fd, char *buffer) {
  921. int x, i;
  922. int need_render = 0; // changing word case around doesn't need the render
  923. int mangled = 0;
  924. char *cp;
  925. // Ok, we want to look for words to:
  926. // MaNGlE , or transpose (both?!)
  927. // or possibly transpose words
  928. char work[(BSIZE * 4) + 1];
  929. ZF_LOGI("mangle(%s)", repr(buffer));
  930. strcpy(work, buffer);
  931. /*
  932. NOTE: We copy the buffer, so we can clear out ANSI codes, etc.
  933. Otherwise we might mess some ANSI up in the manglying
  934. process.
  935. */
  936. /*
  937. (random) Look for ANSI CLS and:
  938. display random spooky texts around, with delays ... then CLS.
  939. display ANSI graphic file, with delays ... then CLS
  940. */
  941. const char *ANSI_CLS = "\x1b[2J";
  942. cp = strstr(buffer, ANSI_CLS);
  943. if (cp != NULL) {
  944. ZF_LOGI("seen: ANSI_CLS");
  945. if (random_activate(9)) {
  946. char display[100] = "";
  947. ZF_LOGI("mangle(ANSI_CLS)");
  948. // sprintf( display, "^P2...");
  949. // This string actually screws up ANSI detection (takes too long)
  950. // strcpy(display, "^P2^S501234567890^P1abcdef^P2g^P3h^P4i^S0^P2");
  951. // strcpy(display, "^P2^S301234^P15^S0^P2");
  952. strcpy(display, "^S3^C1Hi^S0^P1");
  953. // Move the buffer so there's room for the display string.
  954. memmove(cp + strlen(display), cp, strlen(cp) + 1);
  955. strncpy(cp, display, strlen(display));
  956. ZF_LOGI("mangle(ANSI_CLS): (%d) %s", (int)strlen(buffer), repr(buffer));
  957. need_render = 1;
  958. /*
  959. Copy the new buffer over, but hide our "render" code
  960. from the remaining mangler steps.
  961. */
  962. strcpy(work, buffer);
  963. i = cp - buffer;
  964. // find offset into "buffer"
  965. // apply to work.
  966. memset(work + i, ' ', strlen(display));
  967. };
  968. }
  969. /* work -- clear out ANSI so we don't mangle ANSI codes. */
  970. x = rx_match(&ANSI, work);
  971. char replace_with = ' ';
  972. if (x > 0) {
  973. ZF_LOGD("found %d ANSI", x);
  974. for (i = 0; i < x; i++) {
  975. memset(work + rxmatch[i].rm_so, replace_with,
  976. rxmatch[i].rm_eo - rxmatch[i].rm_so);
  977. };
  978. ZF_LOGD("Work Now : (%d) %s", (int)strlen(work), repr(work));
  979. }
  980. // ZF_LOGI("mangle: %s", repr(work));
  981. /*
  982. (random) Locate words (in work), and possibly flip them around.
  983. Transpose words. Transpose case. Transpose letters.
  984. */
  985. x = rx_match(&WORDS, work);
  986. ZF_LOGD("found %d WORDS", x);
  987. if (x > 0) {
  988. for (i = 0; i < x; i++) {
  989. // Do things here.
  990. if (i % 3 == 0) {
  991. for (int p = rxmatch[i].rm_so; p < rxmatch[i].rm_eo; p++) {
  992. buffer[p] = tolower(buffer[p]);
  993. mangled++;
  994. }
  995. } else {
  996. if (i % 3 == 1) {
  997. for (int p = rxmatch[i].rm_so; p < rxmatch[i].rm_eo; p++) {
  998. buffer[p] = toupper(buffer[p]);
  999. mangled++;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. /*
  1006. (random) Locate single words, and transpose them. Transpose case.
  1007. Transpose letters.
  1008. */
  1009. /*
  1010. (random) Display up to certain point. Delay.
  1011. Print some characters slowly. Delay.
  1012. */
  1013. if (need_render) {
  1014. ZF_LOGD("HH %d : (%d) %s", need_render, (int)strlen(buffer), repr(buffer));
  1015. } else {
  1016. if (mangled) {
  1017. ZF_LOGD("Mangled %d : %s", mangled, repr(buffer));
  1018. }
  1019. }
  1020. if (need_render) {
  1021. render(fd, buffer);
  1022. } else {
  1023. write(fd, buffer, strlen(buffer));
  1024. };
  1025. return need_render && mangled;
  1026. }
  1027. int harry_happens(time_t *last_event, int wakeup) {
  1028. time_t now = time(NULL);
  1029. int elapsed = now - *last_event;
  1030. if (elapsed > wakeup) {
  1031. // Ok! It's been too long since we've done something.
  1032. *last_event = now;
  1033. return 1;
  1034. }
  1035. return 0;
  1036. }
  1037. int main(int argc, char *argv[]) {
  1038. int master;
  1039. pid_t pid;
  1040. int node = -1;
  1041. file_output_open("horrible_harry.log");
  1042. init_harry();
  1043. srandom(time(NULL));
  1044. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown -Ubugz
  1045. // -PUWISHPASSWORD
  1046. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  1047. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown -Ubugz
  1048. // -PUP2LAT3
  1049. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  1050. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  1051. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML0 -SL1 -ST0 -CUnknown
  1052. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown -Ubugz
  1053. // -PUP2LAT3
  1054. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML1 -SL1 -ST2 -CUnknown -Ubugz
  1055. // -PUP2LAT3
  1056. // SSH: -ML1 -ST2
  1057. // Telnet: -ML0 -ST0
  1058. // Locate username (if given) in the command line
  1059. // -U<username>
  1060. for (int x = 0; x < argc; x++) {
  1061. if (strncmp("-U", argv[x], 2) == 0) {
  1062. username = argv[x] + 2;
  1063. ZF_LOGI("Username: [%s]", username);
  1064. };
  1065. if (strncmp("-SL", argv[x], 3) == 0) {
  1066. node = argv[x][3] - '0' + 1;
  1067. ZF_LOGI("Node: %d", node);
  1068. }
  1069. }
  1070. if (username != NULL) {
  1071. locate_user(username);
  1072. ZF_LOGD("Username: [%s] A.K.A. [%s]", username, fullname);
  1073. }
  1074. if (!init_regex())
  1075. return 2;
  1076. // With IGNBRK I don't think I need this anymore. (Nope!)
  1077. // signal(SIGINT, SIG_IGN);
  1078. pid = forkpty(&master, NULL, NULL, NULL);
  1079. // impossible to fork
  1080. if (pid < 0) {
  1081. return 1;
  1082. }
  1083. // child
  1084. else if (pid == 0) {
  1085. char *args[20]; // max 20 args
  1086. int x;
  1087. args[0] = TARGET;
  1088. for (x = 1; x < argc; x++) {
  1089. args[x] = argv[x];
  1090. };
  1091. args[x] = NULL;
  1092. // run Mystic, run!
  1093. execvp(TARGET, args);
  1094. }
  1095. // parent
  1096. else {
  1097. // remove the echo
  1098. // ICANON - raw mode. No more line buffering!
  1099. struct termios tios, orig1;
  1100. struct timeval timeout;
  1101. time_t last_event = 0; // time(NULL);
  1102. ZF_LOGD("starting");
  1103. tcgetattr(master, &tios);
  1104. tios.c_lflag &= ~(ECHO | ECHONL | ICANON);
  1105. tcsetattr(master, TCSAFLUSH, &tios);
  1106. tcgetattr(1, &orig1);
  1107. tios = orig1;
  1108. tios.c_iflag &= ~(ICRNL | IXON); // Disable software flow control
  1109. tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  1110. // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
  1111. // ISIG should be Ctrl-C and Ctrl-Z IGNBRK +
  1112. tcsetattr(1, TCSAFLUSH, &tios);
  1113. for (;;) {
  1114. // define estruturas para o select, que serve para verificar qual
  1115. // se tornou "pronto pra uso"
  1116. fd_set read_fd;
  1117. fd_set write_fd;
  1118. fd_set except_fd;
  1119. // inicializa as estruturas
  1120. FD_ZERO(&read_fd);
  1121. FD_ZERO(&write_fd);
  1122. FD_ZERO(&except_fd);
  1123. // atribui o descritor master, obtido pelo forkpty, ao read_fd
  1124. FD_SET(master, &read_fd);
  1125. // atribui o stdin ao read_fd
  1126. FD_SET(STDIN_FILENO, &read_fd);
  1127. // o descritor tem que ser unico para o programa, a documentacao
  1128. // recomenda um calculo entre os descritores sendo usados + 1
  1129. /*
  1130. TODO: Figure out how this would work.
  1131. I'm thinking something like timeouts 30-50 seconds?
  1132. And as we get closer, 15-25 seconds.
  1133. */
  1134. // we're in luck! The last parameter is time interval/timeout. :D
  1135. timeout.tv_sec = 10;
  1136. timeout.tv_usec = 0;
  1137. // select(master+1, &read_fd, &write_fd, &except_fd, NULL);
  1138. if (select(master + 1, &read_fd, &write_fd, &except_fd, &timeout) == 0) {
  1139. // This means timeout!
  1140. ZF_LOGI("TIMEOUT");
  1141. harry_event(STDOUT_FILENO);
  1142. }
  1143. char input[BSIZE + 1];
  1144. static char output[(BSIZE * 4) + 1];
  1145. int total;
  1146. // read_fd esta atribuido com read_fd?
  1147. if (FD_ISSET(master, &read_fd)) {
  1148. // leia o que bc esta mandando
  1149. if ((total = read(master, &output, BSIZE)) != -1) {
  1150. // e escreva isso na saida padrao
  1151. output[total] = 0;
  1152. // if ( harry_happens( &last_event, 5)) {
  1153. if (1) {
  1154. ZF_LOGI("harry_happens");
  1155. if (mangle(STDOUT_FILENO, output) == 0) {
  1156. // failed, so. Try again.
  1157. last_event = 0;
  1158. }
  1159. } else {
  1160. write(STDOUT_FILENO, &output, total);
  1161. // This is OUTPUT from the BBS
  1162. // ZF_LOGI( ">> %s", repr(output));
  1163. ZF_LOGI(">> %d chars", (int)strlen(output));
  1164. // I think repr is flipping out here. :(
  1165. // ZF_LOGI( ">> %d", (int)strlen(repr(output)));
  1166. }
  1167. } else
  1168. break;
  1169. }
  1170. // read_fd esta atribuido com a entrada padrao?
  1171. if (FD_ISSET(STDIN_FILENO, &read_fd)) {
  1172. // leia a entrada padrao
  1173. total = read(STDIN_FILENO, &input, BSIZE);
  1174. input[total] = 0;
  1175. // e escreva no bc
  1176. ZF_LOGI("<< %s", repr(input));
  1177. write(master, &input, total);
  1178. // This is INPUT from the USER
  1179. // ZF_LOGI_MEM( input, strlen(input), "<< ");
  1180. }
  1181. }
  1182. // Restore terminal
  1183. tcsetattr(1, TCSAFLUSH, &orig1);
  1184. ZF_LOGD("exit");
  1185. }
  1186. return 0;
  1187. }