door.go 8.7 KB

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