door.go 13 KB

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