door.go 12 KB

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