door_linux.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. Package door: a golang implementation of a BBS door for linux that
  3. support door32.sys.
  4. import (
  5. "door"
  6. )
  7. int main() {
  8. d = door.Door{}
  9. d.Init() // Process commandline switches, initialize door, detect screen size.
  10. d.Write("Welcome to my awesome door, written in "+door.ColorText("BLINK BOLD WHITE")+"golang"+door.Reset+"."+door.CRNL)
  11. d.Write("Press a key...")
  12. d.Key()
  13. d.Write(door.CRNL)
  14. }
  15. */
  16. package door
  17. import (
  18. "bufio"
  19. "flag"
  20. "fmt"
  21. "log"
  22. "os"
  23. "path/filepath"
  24. "strconv"
  25. "strings"
  26. "syscall"
  27. "time"
  28. )
  29. const CRNL = "\r\n" // BBS Line Ending
  30. const Clrscr = "\x1b[0m\x1b[2J\x1b[H" // Clear screen, home cursor
  31. const HideCursor = "\x1b[?25l" // Hide Cursor
  32. const ShowCursor = "\x1b[?25h" // Show Cursor
  33. var Reset string = Color(0) // ANSI Color Reset
  34. var Unicode bool // Unicode support detected
  35. var CP437 bool // CP437 support detected
  36. var Full_CP437 bool // Full CP437 support detected (handles control codes properly)
  37. var Height int // Screen height detected
  38. var Width int // Screen width detected
  39. var Inactivity int64 = 120 // Inactivity timeout
  40. type FIFOBuffer struct {
  41. data []int
  42. index int
  43. }
  44. func NewFIFOBuffer(maxsize int) FIFOBuffer {
  45. return FIFOBuffer{data: make([]int, maxsize)}
  46. }
  47. func (f *FIFOBuffer) Empty() bool {
  48. return f.index == 0
  49. }
  50. func (f *FIFOBuffer) Push(value int) {
  51. if f.index >= len(f.data) {
  52. log.Panicf("Exceeded FIFOBuffer index %d size %d %#v", f.index, len(f.data), f.data)
  53. }
  54. f.data[f.index] = value
  55. f.index++
  56. }
  57. func (f *FIFOBuffer) Pop() int {
  58. if f.index == 0 {
  59. log.Panicf("Pop from empty FIFOBuffer (size %d).", len(f.data))
  60. }
  61. f.index--
  62. return f.data[f.index]
  63. }
  64. /*
  65. type LIFOBuffer struct {
  66. data []int
  67. index int
  68. }
  69. func (b *LIFOBuffer) Empty() bool {
  70. return b.index == 0
  71. }
  72. func (b *LIFOBuffer) Push(value int) {
  73. if b.index+1 > len(b.data) {
  74. b.data = append(b.data, value)
  75. b.index++
  76. } else {
  77. b.data[b.index] = value
  78. b.index++
  79. }
  80. }
  81. func (b *LIFOBuffer) Pop() int {
  82. if b.index == 0 {
  83. log.Panic("Attempting to Pop from empty LIFOBuffer.")
  84. }
  85. b.index--
  86. return b.data[b.index]
  87. }
  88. */
  89. /*
  90. door32.sys:
  91. 0 Line 1 : Comm type (0=local, 1=serial, 2=telnet)
  92. 0 Line 2 : Comm or socket handle
  93. 38400 Line 3 : Baud rate
  94. Mystic 1.07 Line 4 : BBSID (software name and version)
  95. 1 Line 5 : User record position (1-based)
  96. James Coyle Line 6 : User's real name
  97. g00r00 Line 7 : User's handle/alias
  98. 255 Line 8 : User's security level
  99. 58 Line 9 : User's time left (in minutes)
  100. 1 Line 10: Emulation *See Below
  101. 1 Line 11: Current node number
  102. */
  103. type DropfileConfig struct {
  104. Comm_type int
  105. Comm_handle int
  106. Baudrate int
  107. BBSID string
  108. User_number int
  109. Real_name string
  110. Handle string
  111. Security_level int
  112. Time_left int
  113. Emulation int
  114. Node int
  115. }
  116. type Door struct {
  117. Config DropfileConfig
  118. READFD int
  119. WRITEFD int
  120. Disconnected bool
  121. TimeOut time.Time // Fixed point in time, when time expires
  122. StartTime time.Time
  123. Pushback FIFOBuffer
  124. }
  125. // Return the amount of time left as time.Duration
  126. func (d *Door) TimeLeft() time.Duration {
  127. return time.Until(d.TimeOut)
  128. // return d.TimeOut.Sub(time.Now())
  129. }
  130. func (d *Door) TimeUsed() time.Duration {
  131. return time.Since(d.StartTime)
  132. // return time.Now().Sub(d.StartTime)
  133. }
  134. // Read the BBS door file. We only support door32.sys.
  135. func (d *Door) ReadDropfile(filename string) {
  136. file, err := os.Open(filename)
  137. if err != nil {
  138. log.Panicf("Open(%s): %s\n", filename, err)
  139. // os.Exit(2)
  140. }
  141. defer file.Close()
  142. var lines []string
  143. // read line by line
  144. // The scanner handles DOS and linux file endings.
  145. scanner := bufio.NewScanner(file)
  146. for scanner.Scan() {
  147. line := scanner.Text()
  148. lines = append(lines, line)
  149. }
  150. d.Config.Comm_type, err = strconv.Atoi(lines[0])
  151. d.Config.Comm_handle, err = strconv.Atoi(lines[1])
  152. d.Config.Baudrate, err = strconv.Atoi(lines[2])
  153. d.Config.BBSID = lines[3]
  154. d.Config.User_number, err = strconv.Atoi(lines[4])
  155. d.Config.Real_name = lines[5]
  156. d.Config.Handle = lines[6]
  157. d.Config.Security_level, err = strconv.Atoi(lines[7])
  158. d.Config.Time_left, err = strconv.Atoi(lines[8])
  159. d.Config.Emulation, err = strconv.Atoi(lines[9])
  160. d.Config.Node, err = strconv.Atoi(lines[10])
  161. d.READFD = d.Config.Comm_handle
  162. d.WRITEFD = d.Config.Comm_handle
  163. // Calculate the time when time expires.
  164. d.StartTime = time.Now()
  165. d.TimeOut = time.Now().Add(time.Duration(d.Config.Time_left) * time.Minute)
  166. }
  167. // Detect client terminal capabilities, Unicode, CP437, Full_CP437,
  168. // screen Height and Width.
  169. func (d *Door) detect() {
  170. d.Write("\x1b[0;30;40m\x1b[2J\x1b[H") // black on black, clrscr, go home
  171. d.Write("\x03\x04\x1b[6n") // hearts and diamonds does CP437 work?
  172. d.Write(CRNL + "\u2615\x1b[6n") // hot beverage
  173. d.Write("\x1b[999C\x1b[999B\x1b[6n" + Reset + "\x1b[2J\x1b[H") // goto end of screen + cursor pos
  174. // time.Sleep(50 * time.Millisecond)
  175. time.Sleep(250 * time.Millisecond)
  176. // read everything
  177. // telnet term isn't in RAW mode, so keys are buffer until <CR>
  178. var results string
  179. if d.HasKey() {
  180. buffer := make([]byte, 100)
  181. r, err := syscall.Read(d.READFD, buffer)
  182. if r == -1 {
  183. d.Disconnected = true
  184. return
  185. }
  186. results = string(buffer[:r])
  187. output := strings.Replace(results, "\x1b", "^[", -1)
  188. log.Println("DETECT:", r, err, output)
  189. } else {
  190. // local telnet echos the reply :()
  191. log.Println("DETECT: Nothing received.")
  192. return
  193. }
  194. if (strings.Contains(results, "1;1R") ||
  195. strings.Contains(results, "1;3R")) &&
  196. (strings.Contains(results, "2:2R") ||
  197. strings.Contains(results, "2;3R")) {
  198. Unicode = true
  199. } else {
  200. Unicode = false
  201. CP437 = true
  202. }
  203. if strings.Contains(results, "1;3R") {
  204. Full_CP437 = true
  205. }
  206. // get screen size
  207. pos := strings.LastIndex(results, "\x1b")
  208. if pos != -1 {
  209. pos++
  210. if results[pos] == '[' {
  211. pos++
  212. results = results[pos:]
  213. pos = strings.Index(results, ";")
  214. if pos != -1 {
  215. height := results[:pos]
  216. Height, _ = strconv.Atoi(height)
  217. pos++
  218. results = results[pos:]
  219. pos = strings.Index(results, "R")
  220. if pos != -1 {
  221. width := results[:pos]
  222. Width, _ = strconv.Atoi(width)
  223. // log.Printf("Width: %s, %d, %v\n", results, Width, err)
  224. }
  225. } else {
  226. Height = 0
  227. Width = 0
  228. }
  229. }
  230. }
  231. log.Printf("Unicode %v Screen: %d X %d\n", Unicode, Width, Height)
  232. }
  233. // Initialize door framework. Parse commandline, read dropfile,
  234. // detect terminal capabilities.
  235. func (d *Door) Init(doorname string) {
  236. var dropfile string
  237. d.Pushback = NewFIFOBuffer(5)
  238. // Get path to binary, and chdir to it.
  239. binaryPath, _ := os.Executable()
  240. binaryPath = filepath.Dir(binaryPath)
  241. _ = os.Chdir(binaryPath)
  242. flag.StringVar(&dropfile, "d", "", "Path to dropfile")
  243. flag.Parse()
  244. if len(dropfile) == 0 {
  245. flag.PrintDefaults()
  246. os.Exit(2)
  247. }
  248. d.ReadDropfile(dropfile)
  249. // doorname - node #?
  250. logfilename := fmt.Sprintf("%s-%d.log", doorname, d.Config.Node)
  251. logf, err := os.OpenFile(logfilename, os.O_APPEND|os.O_CREATE|os.O_RDWR, 0666)
  252. if err != nil {
  253. log.Panicf("Error creating log file %s: %v", logfilename, err)
  254. }
  255. log.SetOutput(logf)
  256. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
  257. // log.SetPrefix(doorname + " ")
  258. //= log.New(logf, fmt.Sprintf("%s-%d", doorname, d.Config.Node), log.Ldate|log.Ltime|log.Lshortfile)
  259. log.Printf("Loading dropfile %s\n", dropfile)
  260. 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)
  261. d.detect()
  262. if Unicode {
  263. BOXES = BOXES_UNICODE
  264. BARS = BARS_UNICODE
  265. } else {
  266. BOXES = BOXES_CP437
  267. BARS = BARS_CP437
  268. }
  269. }
  270. func Goto(x int, y int) string {
  271. return fmt.Sprintf("\x1b[%d;%dH", y, x)
  272. }