-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhouston.go
180 lines (147 loc) · 3.78 KB
/
houston.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
package houston
import (
"fmt"
"log"
"mime"
"net"
"net/url"
"os"
"path"
"path/filepath"
"strings"
)
// Strips all NULL chars, and formats to string.
func requestAsString(request []byte) string {
var endIndex int
// Once we hit a NULL char, we know where to
// cut the string off at, and where the CRLF
// will be.
for i, elem := range request {
if elem == 0 {
endIndex = i
break
}
}
newRequest := make([]byte, endIndex-2)
for i := 0; i < endIndex-2; i++ {
newRequest[i] = request[i]
}
return string(newRequest)
}
func GetMimetypeFromPath(targetPath string) string {
extension := path.Ext(targetPath)
if extension == ".gmi" || extension == ".gemini" {
return "text/gemini"
} else {
return mime.TypeByExtension(extension)
}
}
// Get the common part of two paths.
func getSharedPath(path1 string, path2 string) string {
if path1 == "/" && path2 == "/" {
return "/"
}
path1 = path.Clean(path1)
path2 = path.Clean(path2)
var longerPath, shorterPath string
if len(path1) >= len(path2) {
longerPath = path1
shorterPath = path2
} else {
longerPath = path2
shorterPath = path1
}
sharedStr := ""
for i := 0; i < len(shorterPath); i++ {
if shorterPath[i] == longerPath[i] {
sharedStr += string(shorterPath[i])
} else {
if sharedStr == "/" {
sharedStr = ""
}
return sharedStr
}
}
return sharedStr
}
func cleanURLPath(targetUrl string) string {
parsed, _ := url.Parse(targetUrl)
cleaned := path.Clean(parsed.Path)
if cleaned == "." || cleaned == "" || cleaned == " " {
cleaned = "/"
}
return cleaned
}
// Match a URL path to a local path.
func urlToSandboxPath(targetUrl string, sandbox Sandbox) (string, error) {
parsed := cleanURLPath(targetUrl)
localPath := path.Clean(sandbox.LocalPath)
if string(localPath[len(localPath)-1]) != "/" {
localPath += "/"
}
fullLocalPath := strings.Replace(parsed, sandbox.Path, localPath, 1)
fullLocalPath = path.Clean(fullLocalPath)
fileInfo, fileErr := os.Stat(fullLocalPath)
if fileErr == nil && fileInfo.IsDir() {
return filepath.Join(fullLocalPath, "index.gmi"), nil
} else {
return fullLocalPath, nil
}
return "", fileErr
}
func isAllZeroes(bytes []byte) bool {
for _, v := range bytes {
if v != 0 {
return false
}
}
return true
}
func handleConnection(s *Server, c net.Conn) {
data := make([]byte, 1024)
c.Read(data)
if isAllZeroes(data) {
return
}
dataStr := requestAsString(data)
requestParsed, err := url.Parse(dataStr)
if s.Config.EnableLog {
log.Output(1, fmt.Sprintf("%s -> %s", c.RemoteAddr().String(), dataStr))
}
if err != nil {
fmt.Println("Error occurred when parsing URL!")
}
// Usually happens when a bot probes the server with a
// blank HTTP request. This saves it from crashing.
if requestParsed == nil {
c.Close()
log.Output(1, fmt.Sprintf("Ignored request to `%s` and closed connection.", requestParsed))
return
}
context := NewContext(dataStr, c)
// This if statement handles rate-limiting.
if s.Config.EnableLimiting && !allowConnection(s.Config, &context, 1) {
return
}
cleanedPath := cleanURLPath(requestParsed.Path)
handledAsSandbox := false
// First, see if there is a static file to serve
// from a sandbox.
for _, sandbox := range s.Router.Sandboxes {
if getSharedPath(sandbox.Path, cleanedPath) == sandbox.Path {
fullLocalPath, _ := urlToSandboxPath(dataStr, sandbox)
mimeType := GetMimetypeFromPath(fullLocalPath)
if context.SendFile(mimeType, fullLocalPath) == nil {
handledAsSandbox = true
} else if s.Config.ImplyExtension && context.SendFile(mimeType, fullLocalPath + ".gmi") == nil {
handledAsSandbox = true
}
}
}
if !handledAsSandbox {
// Get and call the handler that matches the requested URL.
handler := s.Router.GetRouteHandler(requestParsed.Path)
handler(context)
}
c.Close()
}