-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
295 lines (261 loc) · 10.3 KB
/
server.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
// +build ignore
package main
import (
"./api"
"./cache"
"./util"
"fmt"
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
"strconv"
"strings"
"time"
)
// these two functions are used to process servercmd type GETs
func parseAdditional(additional string) (addTable map[string]string) {
addTable = make(map[string]string)
if additional != "" {
keyValuePairs := strings.Split(strings.TrimSpace(additional), ";")
for _, pair := range keyValuePairs {
if len(pair) > 2 {
parts := strings.SplitN(strings.TrimSpace(additional), ";", 2)
if len(parts) == 2 {
key := strings.TrimSpace(parts[0])
value := strings.TrimSpace(parts[1])
addTable[key] = value
} else {
log.Warnf("Invalid kvPair: %q", pair)
}
}
}
}
return
}
func proxyHandler(c *gin.Context) {
// new proxy request type, used implicitly when the password field is set
// form: /p/fileid=asdf;token=asdf;gid=123;page=321;passkey=asdf/filename
// we allow access depending on the proxy mode retrieved from the server when the client is first started.
// 0 = disabled
// 1 = local networks open
// 2 = external networks open
// 3 = local network protected
// 4 = external network protected
proxymode := 1 //Settings.getRequestProxyMode();
enableProxy := proxymode > 0
requirePasskey := proxymode == 3 || proxymode == 4
requireLocalNetwork := proxymode == 1 || proxymode == 3
if !enableProxy || (requireLocalNetwork /*&& !session.isLocalNetworkAccess()*/) {
log.Warn("Proxy request denied for remote client.")
} else {
parsedRequest := parseAdditional(c.Params.ByName("additional"))
log.Info(parsedRequest)
fileid := parsedRequest["fileid"]
token := parsedRequest["token"]
szGid := parsedRequest["gid"]
szPage := parsedRequest["page"]
passkey := parsedRequest["passkey"]
filename := c.Params.ByName("filename")
acceptPasskey := false
if !requirePasskey {
acceptPasskey = true
} else {
// The client's passkey is generated by passing the client key through a SHA-1
// function together with an additional string. This passkey is then entered under My Settings.
// The request passkey is generated by passing the client passkey through an additional SHA-1 operation,
// which also includes the fileid of the requested file. This gives an unique passkey for each request.
expectedPasskey := "" //util.SHA(fileid +"I think we can put our differences behind us." + util.SHA(Settings.getClientKey() + "For science.")[0:10] +"You monster.")[0:10]
if expectedPasskey == passkey {
acceptPasskey = true
}
//String expectedPasskey = MiscTools.getSHAString(
//fileid + "I think we can put our differences behind us." + MiscTools.getSHAString(Settings.getClientKey() + "For science.").substring(0, 10) + "You monster."
//).substring(0, 10);
}
if !acceptPasskey {
log.Warn("Invalid passkey")
} else {
//if( !(HVFile.isValidHVFileid(fileid) && token.matches("^\\d+-[a-z0-9]{40}$") && szGid.matches("^\\d+$") && szPage.matches("^\\d+$") && filename.matches("^(([a-zA-Z0-9])|(\\.)|(_))*$")) ) {
//Out.warning(session + " Failed argument validation");
gid, _ := strconv.ParseInt(szGid, 10, 0)
page, _ := strconv.ParseInt(szPage, 10, 0)
if gid > 0 && page > 0 {
id, ok := cache.NewIdFromString(fileid)
if ok && CacheHandler.IsExist(id) {
c.Writer.Header().Set("Content-Type", id.MimeType())
file, err := CacheHandler.OpenFileById(id)
if err != nil {
panic(err)
}
defer file.Close()
stat, _ := file.Stat()
http.ServeContent(c.Writer, c.Request, filename, stat.ModTime(), file)
//hpc = new HTTPResponseProcessorFile(requestedHVFile);
log.Infof("try load %q", file)
} else {
//hpc = new HTTPResponseProcessorProxy(session, fileid, token, gid, page, filename);
log.Infof("try proxy %s %s %d %d %s", fileid, token, gid, page, filename)
}
} else {
log.Warn("gid and/or page are <= 0 or not valid integers")
}
}
}
/*
if( !enableProxy || (requireLocalNetwork && !session.isLocalNetworkAccess()) ) {
Out.warning(session + " Proxy request denied for remote client.");
} else {
Hashtable<String,String> parsedRequest = MiscTools.parseAdditional(urlparts[2]);
String fileid = parsedRequest.get("fileid");
String token = parsedRequest.get("token");
String szGid = parsedRequest.get("gid");
String szPage = parsedRequest.get("page");
String passkey = parsedRequest.get("passkey");
String filename = urlparts[3];
boolean acceptPasskey = false;
if(!requirePasskey) {
acceptPasskey = true;
} else if(passkey != null) {
// The client's passkey is generated by passing the client key through a SHA-1 function together with an additional string. This passkey is then entered under My Settings.
// The request passkey is generated by passing the client passkey through an additional SHA-1 operation, which also includes the fileid of the requested file. This gives an unique passkey for each request.
String expectedPasskey = MiscTools.getSHAString(
fileid + "I think we can put our differences behind us." + MiscTools.getSHAString(Settings.getClientKey() + "For science.").substring(0, 10) + "You monster."
).substring(0, 10);
if(expectedPasskey.equals(passkey)) {
acceptPasskey = true;
}
}
if(!acceptPasskey) {
Out.warning(session + " Invalid passkey");
} else if( !(HVFile.isValidHVFileid(fileid) && token.matches("^\\d+-[a-z0-9]{40}$") && szGid.matches("^\\d+$") && szPage.matches("^\\d+$") && filename.matches("^(([a-zA-Z0-9])|(\\.)|(_))*$")) ) {
Out.warning(session + " Failed argument validation");
} else {
try {
int gid = Integer.parseInt(szGid);
int page = Integer.parseInt(szPage);
if(gid > 0 && page > 0) {
HVFile requestedHVFile = session.getHTTPServer().getHentaiAtHomeClient().getCacheHandler().getHVFile(fileid, true);
if( (requestedHVFile != null) && (requestedHVFile.getLocalFileRef().exists()) ) {
hpc = new HTTPResponseProcessorFile(requestedHVFile);
return;
}
else {
hpc = new HTTPResponseProcessorProxy(session, fileid, token, gid, page, filename);
return;
}
}
else {
Out.warning(session + " gid and/or page are <= 0");
}
} catch(Exception e) {
Out.warning(session + " gid and/or page are not valid integers");
}
}
}
*/
}
func xx() {
r := gin.Default()
r.Use(func(c *gin.Context) {
c.Writer.Header().Set("Server", "Genetic Lifeform and Distributed Open Server "+api.CLIENT_VERSION)
//header.append("Date: " + sdf.format(new Date()) + " GMT" + CRLF)
//header.append("Server: Genetic Lifeform and Distributed Open Server " + Settings.CLIENT_VERSION + CRLF)
//header.append("Connection: close" + CRLF)
//header.append("Content-Type: " + hpc.getContentType() + CRLF)
})
r.GET("/h/:hvfile/:additional", func(c *gin.Context) {
})
r.GET("/servercmd", func(c *gin.Context) {
})
r.GET("/p/:additional/:filename", proxyHandler)
r.GET("/t/:size/:time/:key", func(c *gin.Context) {
testsize, _ := strconv.ParseInt(c.Params.ByName("size"), 10, 64)
testtime, _ := strconv.ParseInt(c.Params.ByName("time"), 10, 64)
testkey := c.Params.ByName("key")
//t := time.Unix(time, 0)
log.Debug("Sending threaded proxy test with size=%d time=%d key=%s", testsize, testtime, testkey)
key := fmt.Sprintf("hentai@home-speedtest-%d-%d-%d-%s", testsize, testtime, Client.Id, Client.Key)
if Client.CheckTimeDiff(testtime) {
log.Warn("Got a speedtest request with expired key")
c.String(403, "")
} else if util.SHA(key) != testkey {
log.Warn("Got a speedtest request with invalid key")
c.String(403, "")
} else {
c.Writer.WriteHeader(200)
// FIXME it slow
src := rand.New(rand.NewSource(time.Now().Unix()))
for ; testsize > 0; testsize-- {
c.Writer.Write([]byte{byte(src.Int())})
}
//c.String(200, "")
//hpc = new HTTPResponseProcessorSpeedtest(testsize)
}
})
r.GET("/:name", func(c *gin.Context) {
name := c.Params.ByName("name")
switch name {
case "favicon.ico":
// Redirect to the main website icon (which should already be in the browser cache).
c.Redirect(301, "http://g.e-hentai.org/favicon.ico")
case "robot.txt":
// Bots are not welcome.
c.String(200, "User-agent: *\nDisallow: /")
default:
log.Warn("Invalid request type %s", name)
}
})
/*
if(urlparts(1).equals("h")) {
h(urlparts, localNetworkAccess)
return
}
else if(urlparts(1).equals("servercmd")) {
servercmd(urlparts)
}
else if(urlparts(1).equals("p")) {
p(urlparts)
return
}
else if(urlparts(1).equals("t")) {
// sends a randomly generated file of a given length for speed testing purposes
if(urlparts.length < 5) {
responseStatusCode = 400
} else {
val testsize = urlparts(2).toInt
val testtime = urlparts(3).toInt
val testkey = urlparts(4)
Out.debug("Sending threaded proxy test with testsize=" + testsize + " testtime=" + testtime + " testkey=" + testkey)
if(Math.abs(testtime - Settings.getServerTime()) > Settings.MAX_KEY_TIME_DRIFT) {
Out.warning(session + " Got a speedtest request with expired key")
responseStatusCode = 403
} else if(!MiscTools.getSHAString("hentai@home-speedtest-" + testsize + "-" + testtime + "-" + Settings.getClientID() + "-" + Settings.getClientKey()).equals(testkey)) {
Out.warning(session + " Got a speedtest request with invalid key")
responseStatusCode = 403
} else {
responseStatusCode = 200
hpc = new HTTPResponseProcessorSpeedtest(testsize)
}
}
return
}
else if(urlparts.length == 2) {
if(urlparts(1).equals("favicon.ico")) {
// Redirect to the main website icon (which should already be in the browser cache).
hpc = new HTTPResponseProcessorText("")
hpc.addHeaderField("Location", "http://g.e-hentai.org/favicon.ico")
responseStatusCode = 301 // Moved Permanently
return
}
else if(urlparts(1).equals("robots.txt")) {
// Bots are not welcome.
hpc = new HTTPResponseProcessorText("User-agent: *\nDisallow: /", "text/plain")
responseStatusCode = 200 // Found
return
}
else {
Out.warning(session + " Invalid request type '" + urlparts(1) + "'.")
}
}
*/
}