door.go 13 KB

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