door.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. "strings"
  28. "sync"
  29. "time"
  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. var Unicode bool // Unicode support detected
  39. var CP437 bool // CP437 support detected
  40. var Full_CP437 bool // Full CP437 support detected (handles control codes properly)
  41. var Height int // Screen height detected
  42. var Width int // Screen width detected
  43. var Inactivity int64 = 120 // Inactivity timeout
  44. type CursorPos struct {
  45. X, Y int
  46. }
  47. type Mouse struct {
  48. Button int8
  49. X int8
  50. Y int8
  51. }
  52. /*
  53. door32.sys:
  54. 0 Line 1 : Comm type (0=local, 1=serial, 2=telnet)
  55. 0 Line 2 : Comm or socket handle
  56. 38400 Line 3 : Baud rate
  57. Mystic 1.07 Line 4 : BBSID (software name and version)
  58. 1 Line 5 : User record position (1-based)
  59. James Coyle Line 6 : User's real name
  60. g00r00 Line 7 : User's handle/alias
  61. 255 Line 8 : User's security level
  62. 58 Line 9 : User's time left (in minutes)
  63. 1 Line 10: Emulation *See Below
  64. 1 Line 11: Current node number
  65. */
  66. // Door32 information
  67. type DropfileConfig struct {
  68. Comm_type int // (not used)
  69. Comm_handle int // Handle to use to talk to the user
  70. Baudrate int // (not used)
  71. BBSID string // BBS Software name
  72. User_number int // User number
  73. Real_name string // User's Real Name
  74. Handle string // User's Handle/Nick
  75. Security_level int // Security Level (if given)
  76. Time_left int // Time Left (minutes)
  77. Emulation int // (not used)
  78. Node int // BBS Node number
  79. }
  80. type Door struct {
  81. Config DropfileConfig
  82. READFD int
  83. WRITEFD int
  84. Disconnected bool // int32 // atomic bool // Has User disconnected/Hung up?
  85. TimeOut time.Time // Fixed point in time, when time expires
  86. StartTime time.Time // Time when User started door
  87. Pushback FIFOBuffer // Key buffer
  88. LastColor []int // Track the last color sent for restore color
  89. ReaderClosed bool // Reader close
  90. readerChannel chan byte // Reading from the User
  91. ReaderCanClose bool // We can close the reader (in tests)
  92. WriterClosed bool // Writer closed
  93. writerChannel chan string // Writing to the User
  94. writerMutex sync.RWMutex
  95. LastMouse []Mouse // Store Mouse information
  96. LastCursor []CursorPos // Store Cursor pos information
  97. mcMutex sync.Mutex // Lock for LastMouse, LastCursor
  98. wg sync.WaitGroup
  99. }
  100. func (d *Door) SafeWriterClose() {
  101. d.writerMutex.Lock()
  102. defer d.writerMutex.Unlock()
  103. if !d.WriterClosed {
  104. d.WriterClosed = true
  105. close(d.writerChannel)
  106. }
  107. }
  108. func (d *Door) WriterIsClosed() bool {
  109. d.writerMutex.RLock()
  110. defer d.writerMutex.RUnlock()
  111. return d.WriterClosed
  112. }
  113. func (d *Door) AddMouse(mouse Mouse) {
  114. d.mcMutex.Lock()
  115. defer d.mcMutex.Unlock()
  116. d.LastMouse = append(d.LastMouse, mouse)
  117. }
  118. func (d *Door) GetMouse() (Mouse, bool) {
  119. d.mcMutex.Lock()
  120. defer d.mcMutex.Unlock()
  121. return ArrayDelete(&d.LastMouse, 0)
  122. }
  123. func (d *Door) GetCursorPos() (CursorPos, bool) {
  124. d.mcMutex.Lock()
  125. defer d.mcMutex.Unlock()
  126. return ArrayDelete(&d.LastCursor, 0)
  127. }
  128. func (d *Door) ClearMouseCursor() {
  129. d.mcMutex.Lock()
  130. defer d.mcMutex.Unlock()
  131. d.LastMouse = make([]Mouse, 0, 2)
  132. d.LastCursor = make([]CursorPos, 0, 3)
  133. }
  134. // Return the amount of time left as time.Duration
  135. func (d *Door) TimeLeft() time.Duration {
  136. return time.Until(d.TimeOut)
  137. }
  138. func (d *Door) TimeUsed() time.Duration {
  139. return time.Since(d.StartTime)
  140. }
  141. func (d *Door) Disconnect() bool {
  142. return d.Disconnected // atomic.LoadInt32(&d.Disconnected) != 0
  143. }
  144. // Read the BBS door file. We only support door32.sys.
  145. func (d *Door) ReadDropfile(filename string) {
  146. var file *os.File
  147. var err error
  148. file, err = os.Open(filename)
  149. if err != nil {
  150. log.Panicf("Open(%s): %s\n", filename, err)
  151. }
  152. defer file.Close()
  153. var lines []string
  154. // read line by line
  155. // The scanner handles DOS and linux file endings.
  156. var scanner *bufio.Scanner = bufio.NewScanner(file)
  157. for scanner.Scan() {
  158. line := scanner.Text()
  159. lines = append(lines, line)
  160. }
  161. d.Config.Comm_type, err = strconv.Atoi(lines[0])
  162. if err != nil {
  163. log.Panicf("Door32 Comm Type (expected integer): %s\n", err)
  164. }
  165. d.Config.Comm_handle, err = strconv.Atoi(lines[1])
  166. if err != nil {
  167. log.Panicf("Door32 Comm Handle (expected integer): %s\n", err)
  168. }
  169. d.Config.Baudrate, err = strconv.Atoi(lines[2])
  170. if err != nil {
  171. log.Panicf("Door32 Baudrate (expected integer): %s\n", err)
  172. }
  173. d.Config.BBSID = lines[3]
  174. d.Config.User_number, err = strconv.Atoi(lines[4])
  175. if err != nil {
  176. log.Panicf("Door32 User Number (expected integer): %s\n", err)
  177. }
  178. d.Config.Real_name = lines[5]
  179. d.Config.Handle = lines[6]
  180. d.Config.Security_level, err = strconv.Atoi(lines[7])
  181. if err != nil {
  182. log.Panicf("Door32 Security Level (expected integer): %s\n", err)
  183. }
  184. d.Config.Time_left, err = strconv.Atoi(lines[8])
  185. if err != nil {
  186. log.Panicf("Door32 Time Left (expected integer): %s\n", err)
  187. }
  188. d.Config.Emulation, err = strconv.Atoi(lines[9])
  189. if err != nil {
  190. log.Panicf("Door32 Emulation (expected integer): %s\n", err)
  191. }
  192. d.Config.Node, err = strconv.Atoi(lines[10])
  193. if err != nil {
  194. log.Panicf("Door32 Node Number (expected integer): %s\n", err)
  195. }
  196. d.READFD = d.Config.Comm_handle
  197. d.WRITEFD = d.Config.Comm_handle
  198. d.StartTime = time.Now()
  199. // Calculate when time expires.
  200. d.TimeOut = time.Now().Add(time.Duration(d.Config.Time_left) * time.Minute)
  201. }
  202. // Detect client terminal capabilities, Unicode, CP437, Full_CP437,
  203. // screen Height and Width.
  204. // Full_CP437 means the terminal understands control codes as CP437.
  205. func (d *Door) detect() {
  206. d.Write("\x1b[0;30;40m\x1b[2J\x1b[H") // black on black, clrscr, go home
  207. d.Write("\x03\x04\x1b[6n") // hearts and diamonds does CP437 work?
  208. d.Write(CRNL + "\u2615\x1b[6n") // hot beverage
  209. d.Write("\x1b[999C\x1b[999B\x1b[6n" + Reset + "\x1b[2J\x1b[H") // goto end of screen + cursor pos
  210. // Yuck!
  211. time.Sleep(250 * time.Millisecond)
  212. // read everything
  213. var results string
  214. for {
  215. var r int = d.getch()
  216. if r < 0 {
  217. break
  218. }
  219. results += string(byte(r))
  220. }
  221. if len(results) > 0 {
  222. output := strings.Replace(results, "\x1b", "^[", -1)
  223. log.Println("DETECT:", output)
  224. } else {
  225. log.Println("DETECT: Nothing received.")
  226. return
  227. }
  228. if (strings.Contains(results, "1;1R") ||
  229. strings.Contains(results, "1;3R")) &&
  230. (strings.Contains(results, "2:2R") ||
  231. strings.Contains(results, "2;3R")) {
  232. Unicode = true
  233. } else {
  234. Unicode = false
  235. CP437 = true
  236. }
  237. if strings.Contains(results, "1;3R") {
  238. Full_CP437 = true
  239. }
  240. // get screen size
  241. var pos int = strings.LastIndex(results, "\x1b")
  242. if pos != -1 {
  243. pos++
  244. if results[pos] == '[' {
  245. pos++
  246. results = results[pos:]
  247. pos = strings.Index(results, ";")
  248. if pos != -1 {
  249. var height string = results[:pos]
  250. Height, _ = strconv.Atoi(height)
  251. pos++
  252. results = results[pos:]
  253. pos = strings.Index(results, "R")
  254. if pos != -1 {
  255. width := results[:pos]
  256. Width, _ = strconv.Atoi(width)
  257. }
  258. } else {
  259. Height = 0
  260. Width = 0
  261. }
  262. }
  263. }
  264. log.Printf("Unicode %v Screen: %d X %d\n", Unicode, Width, Height)
  265. }
  266. // Initialize door framework. Parse commandline, read dropfile,
  267. // detect terminal capabilities.
  268. func (d *Door) Init(doorname string) {
  269. var dropfile string
  270. d.Pushback = NewFIFOBuffer(5)
  271. // Get path to binary, and chdir to it.
  272. var binaryPath string
  273. binaryPath, _ = os.Executable()
  274. binaryPath = filepath.Dir(binaryPath)
  275. _ = os.Chdir(binaryPath)
  276. flag.StringVar(&dropfile, "d", "", "Path to dropfile")
  277. flag.Parse()
  278. if len(dropfile) == 0 {
  279. flag.PrintDefaults()
  280. os.Exit(2)
  281. }
  282. d.ReadDropfile(dropfile)
  283. // Logfile will be doorname - node #
  284. var logfilename string = fmt.Sprintf("%s-%d.log", doorname, d.Config.Node)
  285. var logf *os.File
  286. var err error
  287. logf, err = os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
  288. if err != nil {
  289. log.Panicf("Error creating log file %s: %v", logfilename, err)
  290. }
  291. log.SetOutput(logf)
  292. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
  293. log.Printf("Loading dropfile %s\n", dropfile)
  294. 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)
  295. d.readerChannel = make(chan byte, 8)
  296. d.writerChannel = make(chan string) // unbuffered
  297. // changing this to unbound/sync hangs tests.
  298. // d.closeChannel = make(chan struct{}, 2) // reader & door.Close
  299. d.setupChannels()
  300. d.detect()
  301. if Unicode {
  302. BOXES = BOXES_UNICODE
  303. BARS = BARS_UNICODE
  304. } else {
  305. BOXES = BOXES_CP437
  306. BARS = BARS_CP437
  307. }
  308. }
  309. func (d *Door) Close() {
  310. defer func() {
  311. if err := recover(); err != nil {
  312. log.Println("door.Close FAILURE:", err)
  313. // This displays stack trace stderr
  314. debug.PrintStack()
  315. }
  316. }()
  317. log.Println("Closing...")
  318. // d.closeChannel <- struct{}{}
  319. if !d.WriterClosed {
  320. d.writerChannel <- ""
  321. }
  322. // CloseReader(d.Config.Comm_handle)
  323. log.Println("wg.Wait()")
  324. d.wg.Wait()
  325. log.Println("Closed.")
  326. }
  327. // Goto X, Y - Position the cursor using ANSI Escape Codes
  328. //
  329. // Example:
  330. //
  331. // d.Write(door.Goto(1, 5) + "Now at X=1, Y=5.")
  332. func Goto(x int, y int) string {
  333. return fmt.Sprintf("\x1b[%d;%dH", y, x)
  334. }