door.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. Package door: a go implementation of a BBS door for linux and Windows
  3. that uses door32.sys, understand CP437 and unicode (if available),
  4. detects screen size, and supports TheDraw Fonts.
  5. import (
  6. "door"
  7. )
  8. int main() {
  9. d = door.Door{}
  10. d.Init() // Process commandline switches, initialize door, detect screen size.
  11. d.Write("Welcome to my awesome door, written in "+door.ColorText("BLINK BOLD WHITE")+"go"+door.Reset+"."+door.CRNL)
  12. d.Write("Press a key...")
  13. d.Key()
  14. d.Write(door.CRNL)
  15. }
  16. */
  17. package door
  18. import (
  19. "bufio"
  20. "flag"
  21. "fmt"
  22. "log"
  23. "os"
  24. "path/filepath"
  25. "runtime/debug"
  26. "strconv"
  27. "sync"
  28. "time"
  29. )
  30. const SavePos = "\x1b[s" // Save Cursor Position
  31. const RestorePos = "\x1b[u" // Restore Cursor Position
  32. const CRNL = "\r\n" // BBS Line Ending
  33. const Clrscr = "\x1b[0m\x1b[2J\x1b[H" // Clear screen, home cursor
  34. const HideCursor = "\x1b[?25l" // Hide Cursor
  35. const ShowCursor = "\x1b[?25h" // Show Cursor
  36. var Reset string = Color(0) // ANSI Color Reset
  37. const CURSOR_POS = "\x1b[6n"
  38. const SAVE_POS = "\x1b[s"
  39. const RESTORE_POS = "\x1b[u"
  40. // Mouse Clicks (On Click)
  41. const MOUSE_X10 = "\x1b[?9h"
  42. const MOUSE_X10_OFF = "\x1b[?9l"
  43. // Mouse Drags (Up/Down events)
  44. const MOUSE_DRAG = "\x1b[?1000h"
  45. const MOUSE_DRAG_OFF = "\x1b[?1000l"
  46. var Unicode bool // Unicode support detected
  47. var CP437 bool // CP437 support detected
  48. var Full_CP437 bool // Full CP437 support detected (handles control codes properly)
  49. var Height int // Screen height detected
  50. var Width int // Screen width detected
  51. var Inactivity int64 = 120 // Inactivity timeout
  52. type CursorPos struct {
  53. X, Y int
  54. }
  55. type Mouse struct {
  56. Button int8
  57. X int8
  58. Y int8
  59. }
  60. /*
  61. door32.sys:
  62. 0 Line 1 : Comm type (0=local, 1=serial, 2=telnet)
  63. 0 Line 2 : Comm or socket handle
  64. 38400 Line 3 : Baud rate
  65. Mystic 1.07 Line 4 : BBSID (software name and version)
  66. 1 Line 5 : User record position (1-based)
  67. James Coyle Line 6 : User's real name
  68. g00r00 Line 7 : User's handle/alias
  69. 255 Line 8 : User's security level
  70. 58 Line 9 : User's time left (in minutes)
  71. 1 Line 10: Emulation *See Below
  72. 1 Line 11: Current node number
  73. */
  74. // Door32 information
  75. type DropfileConfig struct {
  76. Comm_type int // (not used)
  77. Comm_handle int // Handle to use to talk to the user
  78. Baudrate int // (not used)
  79. BBSID string // BBS Software name
  80. User_number int // User number
  81. Real_name string // User's Real Name
  82. Handle string // User's Handle/Nick
  83. Security_level int // Security Level (if given)
  84. Time_left int // Time Left (minutes)
  85. Emulation int // (not used)
  86. Node int // BBS Node number
  87. }
  88. type Door struct {
  89. Config DropfileConfig
  90. READFD int
  91. WRITEFD int
  92. Disconnected bool // int32 // atomic bool // Has User disconnected/Hung up?
  93. TimeOut time.Time // Fixed point in time, when time expires
  94. StartTime time.Time // Time when User started door
  95. Pushback FIFOBuffer // Key buffer
  96. LastColor []int // Track the last color sent for restore color
  97. ReaderClosed bool // Reader close
  98. readerChannel chan rune // Reading from the User
  99. readerMutex sync.Mutex // Reader close mutex
  100. readerFile *os.File // fd to File
  101. runereader *bufio.Reader // Rune Reader
  102. ReaderCanClose bool // We can close the reader (in tests)
  103. WriterClosed bool // Writer closed
  104. writerChannel chan string // Writing to the User
  105. writerMutex sync.RWMutex
  106. LastMouse []Mouse // Store Mouse information
  107. LastCursor []CursorPos // Store Cursor pos information
  108. mcMutex sync.Mutex // Lock for LastMouse, LastCursor
  109. wg sync.WaitGroup
  110. }
  111. func (d *Door) SafeWriterClose() {
  112. d.writerMutex.Lock()
  113. defer d.writerMutex.Unlock()
  114. if !d.WriterClosed {
  115. d.WriterClosed = true
  116. close(d.writerChannel)
  117. }
  118. }
  119. func (d *Door) WriterIsClosed() bool {
  120. d.writerMutex.RLock()
  121. defer d.writerMutex.RUnlock()
  122. return d.WriterClosed
  123. }
  124. func (d *Door) AddMouse(mouse Mouse) {
  125. d.mcMutex.Lock()
  126. defer d.mcMutex.Unlock()
  127. d.LastMouse = append(d.LastMouse, mouse)
  128. }
  129. func (d *Door) GetMouse() (Mouse, bool) {
  130. d.mcMutex.Lock()
  131. defer d.mcMutex.Unlock()
  132. return ArrayDelete(&d.LastMouse, 0)
  133. }
  134. func (d *Door) GetCursorPos() (CursorPos, bool) {
  135. d.mcMutex.Lock()
  136. defer d.mcMutex.Unlock()
  137. return ArrayDelete(&d.LastCursor, 0)
  138. }
  139. func (d *Door) ClearMouseCursor() {
  140. d.mcMutex.Lock()
  141. defer d.mcMutex.Unlock()
  142. d.LastMouse = make([]Mouse, 0, 2)
  143. d.LastCursor = make([]CursorPos, 0, 3)
  144. }
  145. // Return the amount of time left as time.Duration
  146. func (d *Door) TimeLeft() time.Duration {
  147. return time.Until(d.TimeOut)
  148. }
  149. func (d *Door) TimeUsed() time.Duration {
  150. return time.Since(d.StartTime)
  151. }
  152. func (d *Door) Disconnect() bool {
  153. return d.Disconnected // atomic.LoadInt32(&d.Disconnected) != 0
  154. }
  155. // Read the BBS door file. We only support door32.sys.
  156. func (d *Door) ReadDropfile(filename string) {
  157. var file *os.File
  158. var err error
  159. file, err = os.Open(filename)
  160. if err != nil {
  161. log.Panicf("Open(%s): %s\n", filename, err)
  162. }
  163. defer file.Close()
  164. var lines []string
  165. // read line by line
  166. // The scanner handles DOS and linux file endings.
  167. var scanner *bufio.Scanner = bufio.NewScanner(file)
  168. for scanner.Scan() {
  169. line := scanner.Text()
  170. lines = append(lines, line)
  171. }
  172. d.Config.Comm_type, err = strconv.Atoi(lines[0])
  173. if err != nil {
  174. log.Panicf("Door32 Comm Type (expected integer): %s\n", err)
  175. }
  176. d.Config.Comm_handle, err = strconv.Atoi(lines[1])
  177. if err != nil {
  178. log.Panicf("Door32 Comm Handle (expected integer): %s\n", err)
  179. }
  180. d.Config.Baudrate, err = strconv.Atoi(lines[2])
  181. if err != nil {
  182. log.Panicf("Door32 Baudrate (expected integer): %s\n", err)
  183. }
  184. d.Config.BBSID = lines[3]
  185. d.Config.User_number, err = strconv.Atoi(lines[4])
  186. if err != nil {
  187. log.Panicf("Door32 User Number (expected integer): %s\n", err)
  188. }
  189. d.Config.Real_name = lines[5]
  190. d.Config.Handle = lines[6]
  191. d.Config.Security_level, err = strconv.Atoi(lines[7])
  192. if err != nil {
  193. log.Panicf("Door32 Security Level (expected integer): %s\n", err)
  194. }
  195. d.Config.Time_left, err = strconv.Atoi(lines[8])
  196. if err != nil {
  197. log.Panicf("Door32 Time Left (expected integer): %s\n", err)
  198. }
  199. d.Config.Emulation, err = strconv.Atoi(lines[9])
  200. if err != nil {
  201. log.Panicf("Door32 Emulation (expected integer): %s\n", err)
  202. }
  203. d.Config.Node, err = strconv.Atoi(lines[10])
  204. if err != nil {
  205. log.Panicf("Door32 Node Number (expected integer): %s\n", err)
  206. }
  207. d.READFD = d.Config.Comm_handle
  208. d.WRITEFD = d.Config.Comm_handle
  209. d.StartTime = time.Now()
  210. // Calculate when time expires.
  211. d.TimeOut = time.Now().Add(time.Duration(d.Config.Time_left) * time.Minute)
  212. }
  213. func (d *Door) Detect() bool {
  214. // detect is destructive ... make it non-destructive
  215. // destructive: clears/trashes the screen.
  216. var detect string = "\r\x03\x04" + CURSOR_POS + "\b \b\b \b" +
  217. "\r\u2615" + CURSOR_POS + "\b \b\b \b\b \b" +
  218. SAVE_POS + "\x1b[999C\x1b[999B" + CURSOR_POS + RESTORE_POS
  219. // hot beverage is 3 bytes long -- need 3 "\b \b" to erase.
  220. d.Write(detect)
  221. var info []CursorPos = make([]CursorPos, 0, 3)
  222. var done bool
  223. for !done {
  224. _, ex, err := d.WaitKey(time.Second)
  225. log.Println("WaitKey:", ex, err)
  226. if ex == CURSOR {
  227. cursor, ok := d.GetCursorPos()
  228. if ok {
  229. info = append(info, cursor)
  230. if len(info) == 3 {
  231. done = true
  232. }
  233. }
  234. }
  235. if err != nil {
  236. done = true
  237. }
  238. }
  239. if len(info) != 3 {
  240. // Detection FAILED.
  241. log.Println("Detect FAILED:", info)
  242. return false
  243. }
  244. // Ok! Let's see what we've got...
  245. var valid bool
  246. // Where did I get these numbers from?
  247. // linux term (telnet/ssh) [0].X = 1, [1].X = 3
  248. // VS Code terminal: 1, 3
  249. // https://docs.python.org/3/library/unicodedata.html
  250. // \u2615 is a fullwidth (2 char) unicode symbol!
  251. // SO, [1].X == 3 // and not 2.
  252. // syncterm [0].X = 3, [1].X = 4
  253. // Magiterm [0].X = 3, [1].X = 4
  254. // cp437 + telnet [0].X = 1, [1].X = 4 FullCP437 = False
  255. // ^ Fails FullCP437 test - characters codes ignored.
  256. // cp437plus + telnet 3, 4. (Has FullCP437 support.)
  257. // if (info[0].X == 1 || info[0].X == 3) &&
  258. // (info[1].X == 2 || info[1].X == 3) {
  259. // Breakdown by detected type:
  260. // Unicode \x03 \x04 (control codes ignored)
  261. // Unicode \u2615 = fullwidth takes up 2 characters
  262. // CP437 \x03 \x04 Hearts Diamonds Symbols 2 characters
  263. // ^ Only works for FullCP437
  264. // CP437 \u2615 = b'\xe2\x98\x95' 3 bytes
  265. // So info[1].X = 4
  266. if info[0].X == 1 && info[1].X == 3 {
  267. Unicode = true
  268. valid = true
  269. } else {
  270. // info[1].X = 4
  271. Unicode = false
  272. CP437 = true
  273. valid = true
  274. }
  275. if info[0].X == 3 {
  276. Full_CP437 = true
  277. }
  278. if !valid {
  279. log.Println("Detect FAILED (not valid):", info)
  280. return false
  281. }
  282. Width, Height = info[2].X, info[2].Y
  283. // Putty doesn't seem to restoring the cursor position (when detecting).
  284. d.Write(Goto(1, info[0].Y))
  285. log.Printf("Unicode: %t, CP437: %t, Full %t, Screen %v\n", Unicode, CP437, Full_CP437, info[2])
  286. return true
  287. }
  288. // Detect client terminal capabilities, Unicode, CP437, Full_CP437,
  289. // screen Height and Width.
  290. // Full_CP437 means the terminal understands control codes as CP437.
  291. /*
  292. func (d *Door) old_detect() {
  293. d.Write("\x1b[0;30;40m\x1b[2J\x1b[H") // black on black, clrscr, go home
  294. d.Write("\x03\x04\x1b[6n") // hearts and diamonds does CP437 work?
  295. d.Write(CRNL + "\u2615\x1b[6n") // hot beverage
  296. d.Write("\x1b[999C\x1b[999B\x1b[6n" + Reset + "\x1b[2J\x1b[H") // goto end of screen + cursor pos
  297. // Yuck!
  298. time.Sleep(250 * time.Millisecond)
  299. // read everything
  300. var results string
  301. for {
  302. var r int = d.getch()
  303. if r < 0 {
  304. break
  305. }
  306. results += string(byte(r))
  307. }
  308. if len(results) > 0 {
  309. output := strings.Replace(results, "\x1b", "^[", -1)
  310. log.Println("DETECT:", output)
  311. } else {
  312. log.Println("DETECT: Nothing received.")
  313. return
  314. }
  315. if (strings.Contains(results, "1;1R") ||
  316. strings.Contains(results, "1;3R")) &&
  317. (strings.Contains(results, "2:2R") ||
  318. strings.Contains(results, "2;3R")) {
  319. Unicode = true
  320. } else {
  321. Unicode = false
  322. CP437 = true
  323. }
  324. if strings.Contains(results, "1;3R") {
  325. Full_CP437 = true
  326. }
  327. // get screen size
  328. var pos int = strings.LastIndex(results, "\x1b")
  329. if pos != -1 {
  330. pos++
  331. if results[pos] == '[' {
  332. pos++
  333. results = results[pos:]
  334. pos = strings.Index(results, ";")
  335. if pos != -1 {
  336. var height string = results[:pos]
  337. Height, _ = strconv.Atoi(height)
  338. pos++
  339. results = results[pos:]
  340. pos = strings.Index(results, "R")
  341. if pos != -1 {
  342. width := results[:pos]
  343. Width, _ = strconv.Atoi(width)
  344. }
  345. } else {
  346. Height = 0
  347. Width = 0
  348. }
  349. }
  350. }
  351. log.Printf("Unicode %v Screen: %d X %d\n", Unicode, Width, Height)
  352. }
  353. */
  354. // Initialize door framework. Parse commandline, read dropfile,
  355. // detect terminal capabilities.
  356. func (d *Door) Init(doorname string) {
  357. var dropfile string
  358. d.Pushback = NewFIFOBuffer(5)
  359. // Get path to binary, and chdir to it.
  360. var binaryPath string
  361. binaryPath, _ = os.Executable()
  362. binaryPath = filepath.Dir(binaryPath)
  363. _ = os.Chdir(binaryPath)
  364. flag.StringVar(&dropfile, "d", "", "Path to dropfile")
  365. flag.Parse()
  366. if len(dropfile) == 0 {
  367. flag.PrintDefaults()
  368. os.Exit(2)
  369. }
  370. d.ReadDropfile(dropfile)
  371. // Logfile will be doorname - node #
  372. var logfilename string = fmt.Sprintf("%s-%d.log", doorname, d.Config.Node)
  373. var logf *os.File
  374. var err error
  375. logf, err = os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
  376. if err != nil {
  377. log.Panicf("Error creating log file %s: %v", logfilename, err)
  378. }
  379. log.SetOutput(logf)
  380. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
  381. log.Printf("Loading dropfile %s\n", dropfile)
  382. log.Printf("BBS %s, User %s / Handle %s / File %d\n", d.Config.BBSID, d.Config.Real_name, d.Config.Handle, d.Config.Comm_handle)
  383. d.readerChannel = make(chan rune, 8)
  384. d.writerChannel = make(chan string) // unbuffered
  385. // changing this to unbound/sync hangs tests.
  386. // d.closeChannel = make(chan struct{}, 2) // reader & door.Close
  387. d.setupChannels()
  388. d.Detect()
  389. if Unicode {
  390. BOXES = BOXES_UNICODE
  391. BARS = BARS_UNICODE
  392. } else {
  393. BOXES = BOXES_CP437
  394. BARS = BARS_CP437
  395. }
  396. }
  397. func (d *Door) Close() {
  398. defer func() {
  399. if err := recover(); err != nil {
  400. log.Println("door.Close FAILURE:", err)
  401. // This displays stack trace stderr
  402. debug.PrintStack()
  403. }
  404. }()
  405. log.Println("Closing...")
  406. // d.closeChannel <- struct{}{}
  407. close(d.writerChannel)
  408. /*
  409. if !d.WriterClosed {
  410. d.writerChannel <- ""
  411. }
  412. */
  413. // CloseReader(d.Config.Comm_handle)
  414. log.Println("wg.Wait()")
  415. d.wg.Wait()
  416. log.Println("Closed.")
  417. }
  418. // Goto X, Y - Position the cursor using ANSI Escape Codes
  419. //
  420. // Example:
  421. //
  422. // d.Write(door.Goto(1, 5) + "Now at X=1, Y=5.")
  423. func Goto(x int, y int) string {
  424. return fmt.Sprintf("\x1b[%d;%dH", y, x)
  425. }