door.go 13 KB

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