door.go 12 KB

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