-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspsrv.go
418 lines (371 loc) · 12.1 KB
/
spsrv.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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
flag "github.com/spf13/pflag"
)
type Request struct {
conn io.ReadWriteCloser
netConn *net.Conn
vhost string
user string
path string // Requested path
filePath string // Actual file path that does not include the content dir name
dataLen int
data string
}
const (
statusSuccess = 2
statusRedirect = 3
statusClientError = 4
statusServerError = 5
)
// The following default values are set so that a user would never set any value from the CLI to
// the following. so we can distinguish between user supplied value and the default value.
// The default char is not "" because you can set hostname to "" and it will allow requests to
// any hostname.
// This is not using defaultConf values either because if the config has non-default values, and
// default value is supplied from the CLI, we want to keep taht default value, which is likely what
// user wants.
var cliDefaultChar = ","
var cliDefaultInt = 0
var (
hostname = flag.StringP("hostname", "h", cliDefaultChar, "Hostname")
port = flag.IntP("port", "p", cliDefaultInt, "Port to listen to")
rootDir = flag.StringP("dir", "d", cliDefaultChar, "Root content directory")
confPath = flag.StringP("config", "c", "/etc/spsrv.conf", "Path to config file")
helpFlag = flag.BoolP("help", "?", false, "Get CLI help")
versionFlag = flag.BoolP("version", "v", false, "View version and exit")
)
var (
appVersion = "unknown version"
buildTime = "date unknown"
appCommit = "unknown"
)
func main() {
// Custom usage function because we don't want the "pflag: help requested" message, and
// we don't want to show the default values.
flag.Usage = func() {
fmt.Println(`Usage: spsrv [ [ -c <path> -h <hostname> -p <port> -d <path> ] | --help | --version ]
-c, --config string Path to config file
-d, --dir string Root content directory
-h, --hostname string Hostname
-p, --port int Port to listen to`)
}
flag.Parse()
if *helpFlag {
flag.Usage()
return
}
if *versionFlag {
fmt.Printf("spsrv %s, commit %s, built %s", appVersion, appCommit, buildTime)
return
}
conf, err := LoadConfig(*confPath)
if err != nil {
fmt.Println("Error loading config")
fmt.Println(err.Error())
return
}
// This allows users overriding values in config via the CLI
if *hostname != cliDefaultChar {
conf.Hostname = *hostname
}
if *port != cliDefaultInt {
conf.Port = *port
}
if *rootDir != cliDefaultChar {
conf.RootDir = *rootDir
}
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", conf.Port))
if err != nil {
log.Fatalf("Unable to listen: %s", err)
}
log.Println("✨ You are now running on spsrv ✨")
log.Printf("Listening for connections on port: %d", conf.Port)
serveSpartan(listener, conf)
}
// serveSpartan accepts connections and returns content
func serveSpartan(listener net.Listener, conf *Config) {
for {
// Blocking until request received
conn, err := listener.Accept()
if err != nil {
log.Println("Error accepting connection:", err.Error())
}
log.Println("--> Connection from:", conn.RemoteAddr())
go handleConnection(conn, conf)
}
}
// handleConnection handles a request and does the response
func handleConnection(netConn net.Conn, conf *Config) {
conn := io.ReadWriteCloser(netConn)
// defer conn.Close()
defer func() {
conn.Close()
log.Println("Closed connection")
}()
doneScanningRequest := false
// Check the size of the request buffer.
s := bufio.NewScanner(conn)
s.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if doneScanningRequest {
// Return a byte
return 1, data[:1], nil
}
// Read request
if i := bytes.IndexByte(data, '\n'); i >= 0 {
return i + 1, bytes.TrimRight(data[0:i], "\r"), nil
}
return 0, nil, nil
})
// Sanity check incoming request URL content.
if ok := s.Scan(); !ok {
sendResponseHeader(conn, statusClientError, "Request not valid")
return
}
// Parse request
request := s.Text()
doneScanningRequest = true
log.Println("--> Incoming request: \"" + request + "\"")
host, reqPath, dataLen, err := parseRequest(request)
if err != nil {
log.Println("Bad request")
sendResponseHeader(conn, statusClientError, "Bad request")
return
}
userSubdomainReq := false
if conf.Hostname != "" {
if conf.Hostname != host {
if conf.UserDirEnable && conf.UserSubdomains && strings.HasSuffix(host, conf.Hostname) {
userSubdomainReq = true
}
if !userSubdomainReq {
log.Println("Request host does not match config value Hostname, returning client error.")
sendResponseHeader(conn, statusClientError, "No proxying to other hosts!")
return
}
}
}
if strings.Contains(reqPath, "..") {
log.Println("Returning client error (directory traversal)")
sendResponseHeader(conn, statusClientError, "Stop it with your directory traversal technique!")
return
}
var data string
if dataLen != 0 {
log.Println("Reading data, length", dataLen)
// Read the dataLen amount of data from the data block
var newData string
for s.Scan() {
newData = s.Text()
if len(data)+len(newData) == dataLen {
data += newData
break
}
if len(data)+len(newData) > dataLen {
data += newData[:dataLen-len(data)-1]
}
data += newData
}
}
var vhost string
if userSubdomainReq {
// TODO: Handle extra dots like a.b.host.name?
vhost = strings.TrimSuffix(host, "."+conf.Hostname)
}
req := &Request{vhost: vhost, path: reqPath, netConn: &netConn, conn: conn, data: data, dataLen: dataLen}
// Time to fetch the files!
path := resolvePath(reqPath, conf, req)
// Check for CGI
for _, cgiPath := range conf.CGIPaths {
if strings.HasPrefix(req.filePath, cgiPath) {
if req.user != "" && (!conf.UserCGIEnable || !conf.UserDirEnable) {
break
}
if req.user != "" && (req.filePath == "" || req.filePath == "/") {
// TODO: Refactor - ATM `path` would contain the current CGI file wanted
// But for hitting /~user/, req.filePath is NOT index.gmi
req.filePath = "index.gmi"
}
log.Println("Attempting CGI:", req.filePath)
ok := handleCGI(conf, req, cgiPath)
if ok {
return
}
break // CGI failed. just handle the request as if it's a static file.
}
}
// Reaching here means it is a static file
if dataLen != 0 {
log.Printf("Got data block of length %v for request where CGI not found.", dataLen)
// Not erroring out here because if file not found, return not found rather
// than 'Unexpected input'
}
serveFile(conn, reqPath, path, conf, dataLen != 0)
}
// resolvePath takes in teh request path and returns the cleaned filepath that needs to be fetched.
// It also handles user directories paths /~user/ and /~user if user directories is enabled in the config.
func resolvePath(reqPath string, conf *Config, req *Request) (path string) {
var user string
// Handle user subdomains
if req.vhost != "" {
user = req.vhost
path = reqPath
} else if conf.UserDirEnable && strings.HasPrefix(reqPath, "/~") {
// Handle tildes
// Note that user.host.name/~user/ would treat it as a literal folder named /~user/
// (hence using `else if`)
bits := strings.Split(reqPath, "/")
user = bits[1][1:]
// /~user to /~user/ is somehow able to be handled together with any other /folder to /folder/ redirects
// So I won't worry about that nor handle it specifically
req.filePath = strings.TrimPrefix(filepath.Clean(strings.TrimPrefix(reqPath, "/~"+user)), "/")
path = req.filePath
}
if user != "" {
req.filePath = path
path = filepath.Join("/home/", user, conf.UserDir, path)
req.user = user
if strings.HasSuffix(reqPath, "/") {
path = filepath.Join(path, "index.gmi")
}
return
}
path = reqPath
// TODO: [config] default index file for a directory is index.gmi
if strings.HasSuffix(reqPath, "/") || reqPath == "" {
path = filepath.Join(reqPath, "index.gmi")
}
req.filePath = filepath.Clean(strings.TrimPrefix(path, "/"))
path = filepath.Clean(filepath.Join(conf.RootDir, path))
return
}
// serveFile serves opens the requested path and returns the file content
func serveFile(conn io.ReadWriteCloser, reqPath, path string, conf *Config, hasData bool) {
// If the content directory is not specified as an absolute path, make it absolute.
// prefixDir := ""
// var rootDir http.Dir
// if !strings.HasPrefix(conf.RootDir, "/") {
// prefixDir, _ = os.Getwd()
// }
// Avoid directory traversal type attacks.
// rootDir = http.Dir(prefixDir + strings.Replace(conf.RootDir, ".", "", -1))
// Open the requested resource.
var content []byte
log.Printf("Fetching: %s", path)
f, err := os.Open(path)
if err != nil {
// not putting the /folder to /folder/ redirect here because folder can still
// be opened without errors
// Directory listing
if conf.DirlistEnable && strings.HasSuffix(path, "index.gmi") {
if hasData {
log.Println("Returning client error due to unexpected data block")
sendResponseHeader(conn, statusClientError, "Unexpected input data block received")
return
}
fullPath := path
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
// If and only if the path is index.gmi AND index.gmi does not exist
fullPath = strings.TrimSuffix(fullPath, "index.gmi")
if _, err := os.Stat(fullPath); err == nil {
// If the directly exists
log.Println("Generating directory listing:", fullPath)
content, err = generateDirectoryListing(reqPath, fullPath, conf)
if err != nil {
log.Println(err)
sendResponseHeader(conn, statusServerError, "Error generating directory listing")
return
}
path = strings.TrimSuffix(path, "index.gmi")
serveContent(conn, content, path)
return
}
}
}
log.Println(err)
log.Println("Returning not found")
sendResponseHeader(conn, statusClientError, "Not found")
return
}
defer f.Close()
// Only show this if we are certain that the request was for a static file.
// Which does not include the 'Not found'.
if hasData {
log.Println("Returning client error due to unexpected data block")
sendResponseHeader(conn, statusClientError, "Unexpected input data block received")
return
}
// Read da file
content, err = ioutil.ReadAll(f)
if err != nil {
// /folder to /folder/ redirect
// I wish I could check if err is a "path/to/dir" is a directory error
// but I couldn't figure out how, so this check below is the best I
// can come up with I guess
if _, err := os.Stat(path + "/"); !os.IsNotExist(err) {
log.Println("Redirecting", path, "to", reqPath+"/")
sendResponseHeader(conn, statusRedirect, reqPath+"/")
return
}
log.Println(err)
sendResponseHeader(conn, statusServerError, "Resource could not be read")
return
}
serveContent(conn, content, path)
}
func serveContent(conn io.ReadWriteCloser, content []byte, path string) {
// MIME
meta := http.DetectContentType(content)
if strings.HasSuffix(path, ".gmi") || strings.HasSuffix(path, "/") {
meta = "text/gemini; lang=en; charset=utf-8" // TODO: configure custom meta string
}
log.Println("Serving content:", path)
sendResponseHeader(conn, statusSuccess, meta)
sendResponseContent(conn, content)
}
// func echoFunction(conn io.ReadWriteCloser, content string) {
// sendResponseHeader(conn, statusSuccess, "text/plain")
// sendResponseContent(conn, []byte(content))
// }
func sendResponseHeader(conn io.ReadWriteCloser, statusCode int, meta string) {
header := fmt.Sprintf("%d %s\r\n", statusCode, meta)
_, err := conn.Write([]byte(header))
if err != nil {
log.Printf("There was an error writing to the connection: %s", err)
}
}
func sendResponseContent(conn io.ReadWriteCloser, content []byte) {
_, err := conn.Write(content)
if err != nil {
log.Printf("There was an error writing to the connection: %s", err)
}
}
func parseRequest(r string) (host, path string, contentLength int, err error) {
parts := strings.Split(r, " ")
if len(parts) != 3 {
err = errors.New("Bad request")
return
}
host, path, contentLengthString := parts[0], parts[1], parts[2]
contentLength, err = strconv.Atoi(contentLengthString)
if err != nil {
return
}
return
}