-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
217 lines (179 loc) · 4.95 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
package main
import (
"./session"
"flag"
"fmt"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"strconv"
"strings"
"sync"
)
type sessionTrace interface {
SessionCreated()
SessionClosed()
}
var trace sessionTrace
var (
address = flag.String("address", "localhost:10080", "Bind to address")
ssl = flag.Bool("ssl", false, "Use ssl")
certFile = flag.String("certfile", "cert.pem", "The Cert file")
keyFile = flag.String("keyfile", "key.pem", "The Key file")
pidFile = flag.String("pidfile", "", "The pid file")
multi = flag.Bool("multi", false, "Enable multiple connections for a session")
)
var lock sync.RWMutex
var sessions = make(map[string]*session.Session)
func init() {
mime.AddExtensionType(".map", "application/json")
mime.AddExtensionType(".otf", "font/otf")
mime.AddExtensionType(".eot", "application/vnd.ms-fontobject")
mime.AddExtensionType(".woff", "application/x-font-woff")
mime.AddExtensionType(".svg", "image/svg+xml")
mime.AddExtensionType(".ttf", "font/ttf")
flag.BoolVar(&session.Debugtelnet, "debug", false, "Telnet debugging")
flag.BoolVar(&session.Compression, "compression", false, "Use gzip compression")
flag.BoolVar(&session.SendRemoteIp, "sendremoteip", false, "Send the remote ip to the mud")
flag.IntVar(&session.MaxSessionConnections, "multimaxconn", 2, "Max. connection count per session")
flag.BoolVar(&session.Insecure, "insecure", false, "Plain text connection to avalon server")
flag.StringVar(&session.ServerAddress, "serveraddress", "", "Avalon server address to connect to (defaults to avalon.mud.de:7777/7778")
flag.Parse()
}
func main() {
if *pidFile != "" {
var pid = os.Getpid()
ioutil.WriteFile(*pidFile, []byte(strconv.FormatInt(int64(pid), 10)), os.FileMode(0644))
}
http.HandleFunc("/", func(writer http.ResponseWriter, req *http.Request) {
if req.URL.Path != "" && req.URL.Path != "/" {
writer.Header().Add("Cache-Control", "max-age=31536000, public, no-transform")
}
gzipOk := false
acceptedEncodings := strings.Split(req.Header.Get("Accept-Encoding"), ",")
for _, encoding := range acceptedEncodings {
if encoding == "gzip" {
gzipOk = true
break
}
}
name := "dist" + req.URL.Path
if gzipOk {
file, err := os.Open(name + ".gz")
if err == nil {
writer.Header().Add("Content-Encoding", "gzip")
stat, _ := file.Stat()
http.ServeContent(writer, req, name, stat.ModTime(), file)
file.Close()
return
}
}
http.ServeFile(writer, req, name)
})
notfound := http.NotFoundHandler()
http.HandleFunc("/mud/", func(w http.ResponseWriter, r *http.Request) {
comps := strings.Split(r.URL.Path, "/")
if len(comps) == 4 {
id := comps[2]
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return
}
sess, ok := func(id string) (*session.Session, bool) {
lock.RLock()
defer lock.RUnlock()
sess, ok := sessions[id]
return sess, ok
}(id)
if !ok || sess == nil {
notfound.ServeHTTP(w, r)
return
}
cmd := comps[3]
if cmd == "cmd" {
sess.SendCommand(string(body))
} else if cmd == "naws" {
var w, h int
_, err := fmt.Sscanf(string(body), "%d,%d", &w, &h)
if err == nil {
sess.SendNaws(byte(w), byte(h))
}
} else if cmd == "atcp" {
sess.SendAtcp(string(body))
} else if cmd == "mxp" {
sess.SendMxp(string(body))
}
}
})
http.HandleFunc("/mud", func(w http.ResponseWriter, r *http.Request) {
var sess *session.Session
var sid string
if *multi {
sid = r.URL.Query().Get("sid")
if sid != "" {
if attachToExistingSession(sid, w, r) {
return
}
}
}
var err error
sess, err = session.NewSession(sid, w, r, func() {
lock.Lock()
defer lock.Unlock()
delete(sessions, sess.Id())
log.Printf("session ended %s.", plural(len(sessions)))
if trace != nil {
trace.SessionClosed()
}
})
if err == nil {
lock.Lock()
defer lock.Unlock()
sessions[sess.Id()] = sess
log.Printf("session started %s.", plural(len(sessions)))
if trace != nil {
trace.SessionCreated()
}
} else {
log.Printf("error on session start: %s", err.Error())
}
})
var scheme string
if *ssl {
scheme = "https"
} else {
scheme = "http"
}
fmt.Printf("touche server is running (listening on %s://%s/)\n", scheme, *address)
if *ssl {
log.Fatal(http.ListenAndServeTLS(*address, *certFile, *keyFile, nil))
} else {
log.Fatal(http.ListenAndServe(*address, nil))
}
}
func attachToExistingSession(sid string, w http.ResponseWriter, r *http.Request) bool {
lock.RLock()
defer lock.RUnlock()
sess, ok := sessions[sid]
if !ok {
return false
}
err := sess.Attach(w, r)
if err == nil {
log.Printf("session attached %s.", plural(len(sessions)))
} else {
log.Printf("error on session attach: %s", err.Error())
}
return true
}
func plural(value int) string {
if value == 0 {
return "(no active sessions)"
} else if value == 1 {
return "(1 active session)"
} else {
return "(" + strconv.Itoa(value) + " active sessions)"
}
}