door.go 12 KB

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