mystic.c 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  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. Well SNAP! Mystic numbers don't remotely match ANSI color codes.
  165. 00 : Sets the current foreground to Black 0;30
  166. 01 : Sets the current foreground to Dark Blue 0;34
  167. 02 : Sets the current foreground to Dark Green 0;32
  168. 03 : Sets the current foreground to Dark Cyan 0;36
  169. 04 : Sets the current foreground to Dark Red 0;31
  170. 05 : Sets the current foreground to Dark Magenta 0;35
  171. 06 : Sets the current foreground to Brown 0;33
  172. 07 : Sets the current foreground to Grey 0;37
  173. 08 : Sets the current foreground to Dark Grey 1;30
  174. 09 : Sets the current foreground to Light Blue 1;34
  175. 10 : Sets the current foreground to Light Green 1;32
  176. 11 : Sets the current foreground to Light Cyan 1;36
  177. 12 : Sets the current foreground to Light Red 1;31
  178. 13 : Sets the current foreground to Light Magenta 1;35
  179. 14 : Sets the current foreground to Yellow 1;33
  180. 15 : Sets the current foreground to White 1;37
  181. 16 : Sets the current background to Black 40
  182. 17 : Sets the current background to Blue 44
  183. 18 : Sets the current background to Green 42
  184. 19 : Sets the current background to Cyan 46
  185. 20 : Sets the current background to Red 41
  186. 21 : Sets the current background to Magenta 45
  187. 22 : Sets the current background to Brown 43
  188. 23 : Sets the current background to Grey 47
  189. 24 : Sets the current background to black with blinking foreground 5;40
  190. 25 : Sets the current background to blue with blinking foreground 5;44
  191. 26 : Sets the current background to green with blinking foreground 5;42
  192. 27 : Sets the current background to cyan with blinking foreground 5;46
  193. 28 : Sets the current background to red with blinking foreground 5;41
  194. 29 : Sets the current background to magenta with blinking foreground 5;45
  195. 30 : Sets the current background to brown with blinking foreground 5;43
  196. 31 : Sets the current background to grey with blinking foreground 5;47
  197. Other things that Mystic does ...
  198. [A## - Move the cursor up ## lines
  199. [B## - Move the cursor down ## lines
  200. [C## - Move the cursor forward (to the right) ## columns
  201. [D## - Move the cursor backwards (to the left) ## columns
  202. [K - Clear from the current cursor position to the end of the line
  203. [L - Move cursor and erase data backwards from current column to column ##
  204. [X## - Move cursor to X coordinate ##
  205. [Y## - Move cursor to Y coordinate ##
  206. BS - Sends 1 destructive backspace sequence (ASCII 8-32-8)
  207. CL - Clears the screen (ANSI 1,1 locate and [2J or ASCII 12)
  208. CR - Send a carrage return and line feed (move to next line)
  209. RA - Restore the saved text attribute color
  210. RS - Restore the saved user's terminal screen
  211. SA - Save the current text attribute color
  212. SS - Save the entire user's terminal screen
  213. */
  214. // Covert MYSTIC color to (Proper) ANSI COLOR.
  215. const int MYSTIC[] = { 0, 4, 2, 6, 1, 5, 3, 7};
  216. // ANSI_color = MYSTIC[ odd_mystic_color % 8 ]
  217. void write_color(int fd, int color) {
  218. char buffer[10];
  219. switch (color) {
  220. case 0:
  221. case 1:
  222. case 2:
  223. case 3:
  224. case 4:
  225. case 5:
  226. case 6:
  227. case 7:
  228. sprintf(buffer, "\x1b[0;3%dm", MYSTIC[color]);
  229. break;
  230. case 8:
  231. case 9:
  232. case 10:
  233. case 11:
  234. case 12:
  235. case 13:
  236. case 14:
  237. case 15:
  238. sprintf(buffer, "\x1b[1;3%dm", MYSTIC[color - 8]);
  239. break;
  240. case 16:
  241. case 17:
  242. case 18:
  243. case 19:
  244. case 20:
  245. case 21:
  246. case 22:
  247. case 23:
  248. sprintf(buffer, "\x1b[4%dm", MYSTIC[color - 16]);
  249. break;
  250. case 24:
  251. case 25:
  252. case 26:
  253. case 27:
  254. case 28:
  255. case 29:
  256. case 30:
  257. case 31:
  258. sprintf(buffer, "\x1b[5;4%dm", MYSTIC[color - 24]);
  259. break;
  260. default:
  261. buffer[0] = 0;
  262. break;
  263. }
  264. ZF_LOGD("write_color( %d ): %s", color, repr(buffer));
  265. write(fd, buffer, strlen(buffer));
  266. }
  267. /**
  268. * process_trigger( fd, *cp )
  269. *
  270. * This process a command trigger.
  271. * It has seen TRIGGER, and now it is
  272. * processing whatever comes after it.
  273. * It will perform the process, and
  274. * return the char * of whatever is next.
  275. */
  276. const char *process_trigger(int fd, const char *cp) {
  277. char ch;
  278. int i, x, y;
  279. ch = toupper(*cp);
  280. cp++;
  281. switch (ch) {
  282. case 'D':
  283. i = 0;
  284. if (isdigit(*cp)) {
  285. i = (*cp) - '0';
  286. cp++;
  287. };
  288. if (isdigit(*cp)) {
  289. i *= 10;
  290. i += (*cp) - '0';
  291. cp++;
  292. };
  293. if ((i > 0) && (i < 80)) {
  294. ZF_LOGI("DEL %02d", i);
  295. for (x = 0; x < i; x++) {
  296. write(fd, "\b \b", 3);
  297. }
  298. };
  299. break;
  300. case 'C':
  301. i = 0;
  302. if (isdigit(*cp)) {
  303. i = (*cp) - '0';
  304. cp++;
  305. };
  306. if (isdigit(*cp)) {
  307. i *= 10;
  308. i += (*cp) - '0';
  309. cp++;
  310. };
  311. write_color(fd, i);
  312. break;
  313. case 'G':
  314. x = 0;
  315. if (isdigit(*cp)) {
  316. x = (*cp) - '0';
  317. cp++;
  318. };
  319. if (isdigit(*cp)) {
  320. x *= 10;
  321. x += (*cp) - '0';
  322. cp++;
  323. };
  324. y = 0;
  325. if (isdigit(*cp)) {
  326. y = (*cp) - '0';
  327. cp++;
  328. };
  329. if (isdigit(*cp)) {
  330. y *= 10;
  331. y += (*cp) - '0';
  332. cp++;
  333. };
  334. break;
  335. case 'R':
  336. i = 0;
  337. if (isdigit(*cp)) {
  338. i = (*cp) - '0';
  339. cp++;
  340. };
  341. if ((i > 0) && (i < 10)) {
  342. ZF_LOGI("RENDER %d", i);
  343. current_render.effect = i;
  344. } else {
  345. current_render.effect = 0;
  346. }
  347. break;
  348. case 'S':
  349. i = 0;
  350. if (isdigit(*cp)) {
  351. i = (*cp) - '0';
  352. cp++;
  353. };
  354. if ((i > 0) && (i < 10)) {
  355. ZF_LOGI("SPEED %d", i);
  356. current_render.speed = i;
  357. } else {
  358. current_render.speed = 0;
  359. }
  360. break;
  361. case 'P':
  362. i = 0;
  363. if (isdigit(*cp)) {
  364. i = (*cp) - '0';
  365. cp++;
  366. };
  367. if ((i > 0) && (i < 10)) {
  368. ZF_LOGI("PAWS %d", i);
  369. // sleep(i);
  370. if (!render_overlimit) {
  371. sleep(i);
  372. };
  373. }
  374. break;
  375. }
  376. return cp;
  377. }
  378. /**
  379. * render_effect( fd, ch )
  380. *
  381. * Displays the given character with whatever
  382. * rendering effect is currently active.
  383. * (If any).
  384. */
  385. void render_effect(int fd, char ch) {
  386. int effect = current_render.effect;
  387. int l;
  388. char space = ' ';
  389. char bs = '\b';
  390. switch (effect) {
  391. case 1:
  392. // CHAR + SPC + BS
  393. render_sleep();
  394. write(fd, &ch, 1);
  395. render_sleep();
  396. write(fd, &space, 1);
  397. render_sleep();
  398. render_sleep();
  399. write(fd, &bs, 1);
  400. break;
  401. case 2:
  402. // CHAR + 8 spaces + 8 BS
  403. render_sleep();
  404. write(fd, &ch, 1);
  405. for (l = 0; l < 8; l++) {
  406. render_sleep();
  407. write(fd, &space, 1);
  408. }
  409. for (l = 0; l < 8; l++) {
  410. render_sleep();
  411. write(fd, &bs, 1);
  412. }
  413. break;
  414. case 0:
  415. default:
  416. // NORMAL
  417. render_sleep();
  418. write(fd, &ch, 1);
  419. break;
  420. }
  421. }
  422. /**
  423. * render( fd, string_out )
  424. *
  425. * Render an entire string.
  426. * Handles TRIGGER.
  427. * Renders with effects.
  428. */
  429. void render(int fd, const char *string_out) {
  430. const char *cp = string_out;
  431. const char *trigger = cp;
  432. time_t start = time(NULL);
  433. int elapsed;
  434. int over = 0;
  435. reset_render();
  436. ZF_LOGD("render(%d, %s)", fd, repr(string_out));
  437. // Check our time from time to time.
  438. // If we start running long, disable sleeps.
  439. while ((trigger = strstr(cp, TRIGGER)) != NULL) {
  440. // There is special things to handle in here.
  441. while (cp != trigger) {
  442. elapsed = time(NULL) - start;
  443. if (elapsed > SLEEP_LIMIT) {
  444. render_overlimit = 1;
  445. current_render.speed = 0;
  446. };
  447. // write(fd, cp, 1 );
  448. render_effect(fd, *cp);
  449. cp++;
  450. };
  451. // ZF_LOGI( "at trigger: (%s)", cp);
  452. cp += strlen(TRIGGER);
  453. // Ok, we're pointing at the trigger -- do something.
  454. cp = process_trigger(fd, cp);
  455. // ZF_LOGI( "after trigger: (%s)", cp);
  456. };
  457. // We still might be under a rendering effect.
  458. while (*cp != 0) {
  459. elapsed = time(NULL) - start;
  460. if (elapsed > SLEEP_LIMIT) {
  461. render_overlimit = 1;
  462. current_render.speed = 0;
  463. };
  464. // write(fd, cp, 1);
  465. render_effect(fd, *cp);
  466. cp++;
  467. }
  468. }
  469. // Beanzilla's no repeats
  470. /**
  471. * have_seen( list, len, item )
  472. *
  473. * Returns 1 (true) if item is in the list.
  474. * Rotates the list [x] = [x+1], and
  475. * list[len-1] = item, return 0 (false)
  476. */
  477. int have_seen(int *list, int len, int item) {
  478. int x;
  479. for (x = 0; x < len; x++) {
  480. if (list[x] == item) {
  481. return 1;
  482. }
  483. };
  484. // Ok, it is something different
  485. for (x = 0; x < len - 1; x++) {
  486. list[x] = list[x + 1];
  487. };
  488. list[x] = item;
  489. return 0;
  490. }
  491. /**
  492. * init_have_seen( list, len )
  493. *
  494. * Initialize the have_seen list with -1.
  495. * (-1 isn't a valid index, so we start
  496. * out with all invalid.)
  497. */
  498. void init_have_seen(int *list, int len) {
  499. int x;
  500. for (x = 0; x < len; x++) {
  501. list[x] = -1;
  502. }
  503. }
  504. /*
  505. These are harry "timeout" events.
  506. These happen when we've been sitting around awhile.
  507. */
  508. #define MAX_HARRY_EVENT_DUPS 2
  509. int last_seen_harry_event[MAX_HARRY_EVENT_DUPS];
  510. #ifdef CPP_MADMAN_STL_CODE
  511. const char *random_phrase(const char *words, int len, int last_seen) {
  512. // ooh. a map of char *s to last_seen_events. :P
  513. static map<const char *, array<int>> tracker;
  514. map<const char *, array<int>>::iterator it;
  515. array<int, last_seen> it = tracker.find(words);
  516. if (it == tracker.end()) {
  517. // key does not exist.
  518. array<int, last_seen> last;
  519. for (int i = 0; i < last_seen; i++) {
  520. last[i] = -1;
  521. };
  522. tracker.insert(words, last);
  523. it = tracker.find(words);
  524. };
  525. }
  526. #endif
  527. void harry_event(int fd) {
  528. // Make something happen
  529. char buffer[100];
  530. int r;
  531. // This is no where near finished, BUT!
  532. const char *phrases[] = {"Hahaha", "Snicker, snicker", "Boo!",
  533. "MeOW", "I see U", "Arrooo!",
  534. "Ahh-wooo!", "Aaaooo!"};
  535. const char *cp;
  536. // Remember the last phrase used,
  537. // and don't repeat (the last two)!
  538. do {
  539. r = random() % ((sizeof(phrases) / sizeof(char *)) - 1);
  540. } while (have_seen(last_seen_harry_event, MAX_HARRY_EVENT_DUPS, r));
  541. ZF_LOGD("%d => %d %d", r, last_seen_harry_event[0], last_seen_harry_event[1]);
  542. cp = phrases[r];
  543. int color = random() % 16;
  544. sprintf(buffer, "^S2^C%02d%s^P2^D%02d", color, cp, (int)strlen(cp));
  545. ZF_LOGD("harry_event: render(%d, \"%s\")", fd, buffer);
  546. render(fd, buffer);
  547. }
  548. void init_harry() {
  549. init_have_seen(last_seen_harry_event, MAX_HARRY_EVENT_DUPS);
  550. ZF_LOGD("init => %d %d", last_seen_harry_event[0], last_seen_harry_event[1]);
  551. }
  552. /*
  553. The code to get the username and fullname is useless on telnet
  554. connections.
  555. */
  556. char *username = NULL;
  557. char *fullname = NULL;
  558. /*
  559. Pascal String Copy. Copy from pascal string, to C String.
  560. First char is pascal string length. (Max 255).
  561. */
  562. void pcopy(char *pstring, char *str) {
  563. int len = (int)*pstring;
  564. strncpy(str, pstring + 1, len);
  565. str[len] = 0;
  566. }
  567. /*
  568. This only works for those few idiots that use the
  569. horribly broken SSH crap that Mystic uses.
  570. */
  571. int locate_user(const char *alias) {
  572. FILE *user;
  573. char buffer[0x600];
  574. char temp[100];
  575. user = fopen("data/users.dat", "rb");
  576. if (user == NULL)
  577. return 0;
  578. // Carry on!
  579. while (fread(buffer, 0x600, 1, user) == 1) {
  580. pcopy(buffer + 0x6d, temp);
  581. if (strcasecmp(temp, username) == 0) {
  582. pcopy(buffer + 0x8c, temp);
  583. fullname = strdup(temp);
  584. break;
  585. }
  586. /*
  587. printf("Alias: %s\n", temp);
  588. pcopy(buffer + 0x8c, temp );
  589. printf("Full Name: %s\n", temp );
  590. */
  591. }
  592. fclose(user);
  593. return 1;
  594. }
  595. // Buffers are BSIZE + 1, so a buffer that size can strcpy safely.
  596. regex_t ANSI;
  597. regex_t WORDS;
  598. regex_t WORD;
  599. int init_regex(void) {
  600. int ret;
  601. char ansi[] = "\x1b\[[0-9]+(;[0-9]+)*?[a-zA-Z]";
  602. char words[] = "[a-zA-Z]+( [a-zA-Z]+)+";
  603. char word[] = "[a-zA-Z]+";
  604. char errorbuf[100];
  605. if (ret = regcomp(&ANSI, ansi, REG_EXTENDED | REG_NEWLINE)) {
  606. regerror(ret, &ANSI, errorbuf, sizeof(errorbuf));
  607. ZF_LOGW("Regex %s failed to compile: %s", ansi, errorbuf);
  608. return 0;
  609. };
  610. if (ret = regcomp(&WORDS, words, REG_EXTENDED | REG_NEWLINE)) {
  611. regerror(ret, &WORDS, errorbuf, sizeof(errorbuf));
  612. ZF_LOGW("Regex %s failed to compile: %s", words, errorbuf);
  613. return 0;
  614. };
  615. if (ret = regcomp(&WORD, word, REG_EXTENDED | REG_NEWLINE)) {
  616. regerror(ret, &WORD, errorbuf, sizeof(errorbuf));
  617. ZF_LOGW("Regex %s failed to compile: %s", word, errorbuf);
  618. return 0;
  619. };
  620. return 1;
  621. }
  622. int regmatch(regex_t *preg, const char *string, size_t nmatch,
  623. regmatch_t pmatch[], int eflags) {
  624. // returns number of matches found. (Max nmatch)
  625. int matches = 0;
  626. int offset = 0;
  627. int ret;
  628. while (matches < nmatch) {
  629. ret = regexec(preg, string + offset, nmatch - matches, pmatch + matches,
  630. eflags);
  631. if (!ret) {
  632. int current = offset;
  633. offset += pmatch[matches].rm_eo;
  634. pmatch[matches].rm_so += current;
  635. pmatch[matches].rm_eo += current;
  636. matches++;
  637. } else if (ret == REG_NOMATCH) {
  638. break;
  639. } else {
  640. break;
  641. }
  642. }
  643. return matches;
  644. }
  645. #define MAX_MATCH 32
  646. regmatch_t rxmatch[MAX_MATCH];
  647. int rx_match(regex_t *regex, const char *buffer) {
  648. int ret;
  649. ret = regmatch(regex, buffer, MAX_MATCH, rxmatch, 0);
  650. if (0) {
  651. for (int i = 0; i < ret; i++) {
  652. ZF_LOGI("%d : (%d-%d)", i, rxmatch[i].rm_so, rxmatch[i].rm_eo);
  653. }
  654. }
  655. return ret;
  656. }
  657. /*
  658. Terminal processing section.
  659. Monitor lines, position, color.
  660. What screen size do I want to emulate?
  661. ANSI codes.
  662. Do I need this??
  663. */
  664. int random_activate(int w) {
  665. int r = random() % 100;
  666. if (r <= (w * 10)) {
  667. return 1;
  668. };
  669. return 0;
  670. }
  671. /*
  672. * The buffer that we've been given is much larger now.
  673. *
  674. */
  675. int mangle(int fd, char *buffer) {
  676. int x, i;
  677. int need_render = 0; // changing word case around doesn't need the render
  678. int mangled = 0;
  679. char *cp;
  680. // Ok, we want to look for words to:
  681. // MaNGlE , or transpose (both?!)
  682. // or possibly transpose words
  683. char work[(BSIZE * 4) + 1];
  684. ZF_LOGI("mangle(%s)", repr(buffer));
  685. strcpy(work, buffer);
  686. /*
  687. NOTE: We copy the buffer, so we can clear out ANSI codes, etc.
  688. Otherwise we might mess some ANSI up in the manglying
  689. process.
  690. */
  691. /*
  692. (random) Look for ANSI CLS and:
  693. display random spooky texts around, with delays ... then CLS.
  694. display ANSI graphic file, with delays ... then CLS
  695. */
  696. const char *ANSI_CLS = "\x1b[2J";
  697. cp = strstr(buffer, ANSI_CLS);
  698. if (cp != NULL) {
  699. ZF_LOGI("seen: ANSI_CLS");
  700. if (random_activate(9)) {
  701. char display[100] = "";
  702. ZF_LOGI("mangle(ANSI_CLS)");
  703. // sprintf( display, "^P2...");
  704. // This string actually screws up ANSI detection (takes too long)
  705. // strcpy(display, "^P2^S501234567890^P1abcdef^P2g^P3h^P4i^S0^P2");
  706. strcpy(display, "^P2^S301234^P15^S0^P2");
  707. // Move the buffer so there's room for the display string.
  708. memmove(cp + strlen(display), cp, strlen(cp) + 1);
  709. strncpy(cp, display, strlen(display));
  710. ZF_LOGI("mangle(ANSI_CLS): (%d) %s", (int)strlen(buffer), repr(buffer));
  711. need_render = 1;
  712. /*
  713. Copy the new buffer over, but hide our "render" code
  714. from the remaining mangler steps.
  715. */
  716. strcpy(work, buffer);
  717. i = cp - buffer;
  718. // find offset into "buffer"
  719. // apply to work.
  720. memset(work + i, ' ', strlen(display));
  721. };
  722. }
  723. /* work -- clear out ANSI so we don't mangle ANSI codes. */
  724. x = rx_match(&ANSI, work);
  725. char replace_with = ' ';
  726. if (x > 0) {
  727. ZF_LOGD("found %d ANSI", x);
  728. for (i = 0; i < x; i++) {
  729. memset(work + rxmatch[i].rm_so, replace_with,
  730. rxmatch[i].rm_eo - rxmatch[i].rm_so);
  731. };
  732. ZF_LOGD("Work Now : (%d) %s", (int)strlen(work), repr(work));
  733. }
  734. // ZF_LOGI("mangle: %s", repr(work));
  735. /*
  736. (random) Locate words (in work), and possibly flip them around.
  737. Transpose words. Transpose case. Transpose letters.
  738. */
  739. x = rx_match(&WORDS, work);
  740. ZF_LOGD("found %d WORDS", x);
  741. if (x > 0) {
  742. for (i = 0; i < x; i++) {
  743. // Do things here.
  744. if (i % 3 == 0) {
  745. for (int p = rxmatch[i].rm_so; p < rxmatch[i].rm_eo; p++) {
  746. buffer[p] = tolower(buffer[p]);
  747. mangled++;
  748. }
  749. } else {
  750. if (i % 3 == 1) {
  751. for (int p = rxmatch[i].rm_so; p < rxmatch[i].rm_eo; p++) {
  752. buffer[p] = toupper(buffer[p]);
  753. mangled++;
  754. }
  755. }
  756. }
  757. }
  758. }
  759. /*
  760. (random) Locate single words, and transpose them. Transpose case.
  761. Transpose letters.
  762. */
  763. /*
  764. (random) Display up to certain point. Delay.
  765. Print some characters slowly. Delay.
  766. */
  767. if (need_render) {
  768. ZF_LOGD("HH %d : (%d) %s", need_render, (int)strlen(buffer), repr(buffer));
  769. } else {
  770. if (mangled) {
  771. ZF_LOGD("Mangled %d : %s", mangled, repr(buffer));
  772. }
  773. }
  774. if (need_render) {
  775. render(fd, buffer);
  776. } else {
  777. write(fd, buffer, strlen(buffer));
  778. };
  779. return need_render && mangled;
  780. }
  781. int harry_happens(time_t *last_event, int wakeup) {
  782. time_t now = time(NULL);
  783. int elapsed = now - *last_event;
  784. if (elapsed > wakeup) {
  785. // Ok! It's been too long since we've done something.
  786. *last_event = now;
  787. return 1;
  788. }
  789. return 0;
  790. }
  791. int main(int argc, char *argv[]) {
  792. int master;
  793. pid_t pid;
  794. int node = -1;
  795. file_output_open("horrible_harry.log");
  796. init_harry();
  797. srandom(time(NULL));
  798. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown -Ubugz
  799. // -PUWISHPASSWORD
  800. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  801. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown -Ubugz
  802. // -PUP2LAT3
  803. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  804. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML0 -SL0 -ST0 -CUnknown
  805. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML0 -SL1 -ST0 -CUnknown
  806. // ./mystic -TID7 -IP192.168.0.1 -HOSTUnknown -ML1 -SL0 -ST2 -CUnknown -Ubugz
  807. // -PUP2LAT3
  808. // ./mystic -TID9 -IP192.168.0.1 -HOSTUnknown -ML1 -SL1 -ST2 -CUnknown -Ubugz
  809. // -PUP2LAT3
  810. // SSH: -ML1 -ST2
  811. // Telnet: -ML0 -ST0
  812. // Locate username (if given) in the command line
  813. // -U<username>
  814. for (int x = 0; x < argc; x++) {
  815. if (strncmp("-U", argv[x], 2) == 0) {
  816. username = argv[x] + 2;
  817. ZF_LOGI("Username: [%s]", username);
  818. };
  819. if (strncmp("-SL", argv[x], 3) == 0) {
  820. node = argv[x][3] - '0' + 1;
  821. ZF_LOGI("Node: %d", node);
  822. }
  823. }
  824. if (username != NULL) {
  825. locate_user(username);
  826. ZF_LOGD("Username: [%s] A.K.A. [%s]", username, fullname);
  827. }
  828. if (!init_regex())
  829. return 2;
  830. // With IGNBRK I don't think I need this anymore. (Nope!)
  831. // signal(SIGINT, SIG_IGN);
  832. pid = forkpty(&master, NULL, NULL, NULL);
  833. // impossible to fork
  834. if (pid < 0) {
  835. return 1;
  836. }
  837. // child
  838. else if (pid == 0) {
  839. char *args[20]; // max 20 args
  840. int x;
  841. args[0] = TARGET;
  842. for (x = 1; x < argc; x++) {
  843. args[x] = argv[x];
  844. };
  845. args[x] = NULL;
  846. // run Mystic, run!
  847. execvp(TARGET, args);
  848. }
  849. // parent
  850. else {
  851. // remove the echo
  852. // ICANON - raw mode. No more line buffering!
  853. struct termios tios, orig1;
  854. struct timeval timeout;
  855. time_t last_event = 0; // time(NULL);
  856. ZF_LOGD("starting");
  857. tcgetattr(master, &tios);
  858. tios.c_lflag &= ~(ECHO | ECHONL | ICANON);
  859. tcsetattr(master, TCSAFLUSH, &tios);
  860. tcgetattr(1, &orig1);
  861. tios = orig1;
  862. tios.c_iflag &= ~(ICRNL | IXON); // Disable software flow control
  863. tios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
  864. // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html
  865. // ISIG should be Ctrl-C and Ctrl-Z IGNBRK +
  866. tcsetattr(1, TCSAFLUSH, &tios);
  867. for (;;) {
  868. // define estruturas para o select, que serve para verificar qual
  869. // se tornou "pronto pra uso"
  870. fd_set read_fd;
  871. fd_set write_fd;
  872. fd_set except_fd;
  873. // inicializa as estruturas
  874. FD_ZERO(&read_fd);
  875. FD_ZERO(&write_fd);
  876. FD_ZERO(&except_fd);
  877. // atribui o descritor master, obtido pelo forkpty, ao read_fd
  878. FD_SET(master, &read_fd);
  879. // atribui o stdin ao read_fd
  880. FD_SET(STDIN_FILENO, &read_fd);
  881. // o descritor tem que ser unico para o programa, a documentacao
  882. // recomenda um calculo entre os descritores sendo usados + 1
  883. /*
  884. TODO: Figure out how this would work.
  885. I'm thinking something like timeouts 30-50 seconds?
  886. And as we get closer, 15-25 seconds.
  887. */
  888. // we're in luck! The last parameter is time interval/timeout. :D
  889. timeout.tv_sec = 10;
  890. timeout.tv_usec = 0;
  891. // select(master+1, &read_fd, &write_fd, &except_fd, NULL);
  892. if (select(master + 1, &read_fd, &write_fd, &except_fd, &timeout) == 0) {
  893. // This means timeout!
  894. ZF_LOGI("TIMEOUT");
  895. harry_event(STDOUT_FILENO);
  896. }
  897. char input[BSIZE + 1];
  898. static char output[(BSIZE * 4) + 1];
  899. int total;
  900. // read_fd esta atribuido com read_fd?
  901. if (FD_ISSET(master, &read_fd)) {
  902. // leia o que bc esta mandando
  903. if ((total = read(master, &output, BSIZE)) != -1) {
  904. // e escreva isso na saida padrao
  905. output[total] = 0;
  906. // if ( harry_happens( &last_event, 5)) {
  907. if (1) {
  908. ZF_LOGI("harry_happens");
  909. if (mangle(STDOUT_FILENO, output) == 0) {
  910. // failed, so. Try again.
  911. last_event = 0;
  912. }
  913. } else {
  914. write(STDOUT_FILENO, &output, total);
  915. // This is OUTPUT from the BBS
  916. // ZF_LOGI( ">> %s", repr(output));
  917. ZF_LOGI(">> %d chars", (int)strlen(output));
  918. // I think repr is flipping out here. :(
  919. // ZF_LOGI( ">> %d", (int)strlen(repr(output)));
  920. }
  921. } else
  922. break;
  923. }
  924. // read_fd esta atribuido com a entrada padrao?
  925. if (FD_ISSET(STDIN_FILENO, &read_fd)) {
  926. // leia a entrada padrao
  927. total = read(STDIN_FILENO, &input, BSIZE);
  928. input[total] = 0;
  929. // e escreva no bc
  930. ZF_LOGI("<< %s", repr(input));
  931. write(master, &input, total);
  932. // This is INPUT from the USER
  933. // ZF_LOGI_MEM( input, strlen(input), "<< ");
  934. }
  935. }
  936. // Restore terminal
  937. tcsetattr(1, TCSAFLUSH, &orig1);
  938. ZF_LOGD("exit");
  939. }
  940. return 0;
  941. }