mystic.cpp 39 KB

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