door.go 12 KB

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