door.go 9.0 KB

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