mystic.c 37 KB

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