door.go 9.1 KB

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