-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmain.go
More file actions
623 lines (549 loc) · 18.1 KB
/
main.go
File metadata and controls
623 lines (549 loc) · 18.1 KB
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package main
import (
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"path"
"slices"
"strconv"
"strings"
"time"
)
type (
THttpHandler = func(Context *THttpRequestContext)
THttpRoute struct {
Method string
Prefix string
AllowParams bool
Handler THttpHandler
}
THttpRouter struct {
Routes []THttpRoute
NotFound THttpHandler
}
THttpRequestContext struct {
Request *http.Request
Writer http.ResponseWriter
Prefix string
Params []string
IPAddress string
SessionID []byte
AccountID int
}
)
var (
// HTTP/HTTPS Config
g_HttpPort int = 80
g_HttpsPort int = 443
g_HttpsCertFile string = ""
g_HttpsKeyFile string = ""
// SMTP Config
g_SmtpHost string = "smtp.domain.com"
g_SmtpPort int = 587
g_SmtpUser string = "username"
g_SmtpPassword string = ""
// Query Manager Config
g_QueryManagerHost string = "localhost"
g_QueryManagerPort int = 7174
g_QueryManagerPassword string = ""
// Query Manager Cache Config
g_MaxCachedAccounts = 4096
g_MaxCachedCharacters = 4096
g_CharacterRefreshInterval = 15 * time.Minute
g_WorldRefreshInterval = 15 * time.Minute
// Loggers
g_Log = log.New(os.Stderr, "INFO ", log.Ldate|log.Ltime|log.Lmsgprefix)
g_LogWarn = log.New(os.Stderr, "WARN ", log.Ldate|log.Ltime|log.Lshortfile|log.Lmsgprefix)
g_LogErr = log.New(os.Stderr, "ERR ", log.Ldate|log.Ltime|log.Lshortfile|log.Lmsgprefix)
)
func WebKVCallback(Key string, Value string) {
if strings.EqualFold(Key, "HttpPort") {
g_HttpPort = ParseInteger(Value)
} else if strings.EqualFold(Key, "HttpsPort") {
g_HttpsPort = ParseInteger(Value)
} else if strings.EqualFold(Key, "HttpsCertFile") {
g_HttpsCertFile = ParseString(Value)
} else if strings.EqualFold(Key, "HttpsKeyFile") {
g_HttpsKeyFile = ParseString(Value)
} else if strings.EqualFold(Key, "SmtpHost") {
g_SmtpHost = ParseString(Value)
} else if strings.EqualFold(Key, "SmtpPort") {
g_SmtpPort = ParseInteger(Value)
} else if strings.EqualFold(Key, "SmtpUser") {
g_SmtpUser = ParseString(Value)
} else if strings.EqualFold(Key, "SmtpPassword") {
g_SmtpPassword = ParseString(Value)
} else if strings.EqualFold(Key, "SmtpSender") {
g_SmtpSender = ParseString(Value)
} else if strings.EqualFold(Key, "QueryManagerHost") {
g_QueryManagerHost = ParseString(Value)
} else if strings.EqualFold(Key, "QueryManagerPort") {
g_QueryManagerPort = ParseInteger(Value)
} else if strings.EqualFold(Key, "QueryManagerPassword") {
g_QueryManagerPassword = ParseString(Value)
} else if strings.EqualFold(Key, "MaxCachedAccounts") {
g_MaxCachedAccounts = ParseInteger(Value)
} else if strings.EqualFold(Key, "MaxCachedCharacters") {
g_MaxCachedCharacters = ParseInteger(Value)
} else if strings.EqualFold(Key, "CharacterRefreshInterval") {
g_CharacterRefreshInterval = ParseDuration(Value)
} else if strings.EqualFold(Key, "WorldRefreshInterval") {
g_WorldRefreshInterval = ParseDuration(Value)
} else {
g_LogWarn.Printf("Unknown config \"%v\"", Key)
}
}
func (Route *THttpRoute) LessThan(Method string, Prefix string, AllowParams bool) bool {
if Route.Method != Method {
return Route.Method < Method
} else if Route.Prefix != Prefix {
return Route.Prefix < Prefix
} else {
// NOTE(fusion): Use `false < true` convention.
return !Route.AllowParams && AllowParams
}
}
func (Router *THttpRouter) Add(Method string, Prefix string, Handler THttpHandler) {
AllowParams := false
if Prefix != "/" && Prefix[len(Prefix)-1] == '/' {
AllowParams = true
Prefix = Prefix[:len(Prefix)-1]
}
Index := 0
for ; Index < len(Router.Routes); Index += 1 {
if !Router.Routes[Index].LessThan(Method, Prefix, AllowParams) {
break
}
}
if Index < len(Router.Routes) &&
Router.Routes[Index].Method == Method &&
Router.Routes[Index].Prefix == Prefix &&
Router.Routes[Index].AllowParams == AllowParams {
if AllowParams {
g_LogErr.Printf("Discarding duplicate route \"%v %v[/params]\"",
Method, Prefix)
} else {
g_LogErr.Printf("Discarding duplicate route \"%v %v\"",
Method, Prefix)
}
return
}
Router.Routes = slices.Insert(Router.Routes, Index,
THttpRoute{
Method: Method,
Prefix: Prefix,
AllowParams: AllowParams,
Handler: Handler,
})
}
func GetRequestIPAddress(Request *http.Request) string {
// NOTE(fusion): `Request.RemoteAddr` should to be in the exact format
// expected by `net.SplitHostPort` so I expect this to NEVER fail.
IPAddress, _, Err := net.SplitHostPort(Request.RemoteAddr)
if Err != nil {
g_LogErr.Printf("net.SplitHostPort(\"%v\") failed: %v", Request.RemoteAddr, Err)
return ""
}
return IPAddress
}
func (Router *THttpRouter) ServeHTTP(Writer http.ResponseWriter, Request *http.Request) {
Path := Request.URL.Path
if Path == "" {
Path = "/"
}
IPAddress := GetRequestIPAddress(Request)
if IPAddress == "" {
http.Error(Writer, "", http.StatusBadRequest)
return
}
SessionID := GetRequestSessionID(Request)
Context := THttpRequestContext{
Request: Request,
Writer: Writer,
Prefix: Path,
Params: nil,
IPAddress: IPAddress,
SessionID: SessionID,
AccountID: SessionLookup(SessionID, IPAddress),
}
for Index := len(Router.Routes) - 1; Index >= 0; Index -= 1 {
Route := &Router.Routes[Index]
if Route.Method != "" && Route.Method != Request.Method {
continue
}
Suffix, Found := strings.CutPrefix(Path, Route.Prefix)
if Found && (Suffix == "" || Suffix[0] == '/') {
Params := SplitDiscardEmpty(Suffix, "/")
if Route.AllowParams || len(Params) == 0 {
Context.Prefix = Route.Prefix
Context.Params = Params
Route.Handler(&Context)
return
}
}
}
Router.NotFound(&Context)
}
func Redirect(Context *THttpRequestContext, Path string) {
Context.Writer.Header().Set("Location", Path)
Context.Writer.WriteHeader(http.StatusTemporaryRedirect)
}
func RequestError(Context *THttpRequestContext, Status int) {
g_LogErr.Printf("Failed to serve request \"%v %v\" to \"%v\": (%v) %v",
Context.Request.Method, Context.Request.URL.Path, Context.Request.RemoteAddr,
Status, http.StatusText(Status))
RenderRequestError(Context, Status)
}
func BadRequest(Context *THttpRequestContext) {
RequestError(Context, http.StatusBadRequest)
}
func Forbidden(Context *THttpRequestContext) {
RequestError(Context, http.StatusForbidden)
}
func NotFound(Context *THttpRequestContext) {
RequestError(Context, http.StatusNotFound)
}
func InternalError(Context *THttpRequestContext) {
RequestError(Context, http.StatusInternalServerError)
}
func ResourceError(Context *THttpRequestContext, Status int) {
// IMPORTANT(fusion): This is used for resource errors in which case we
// don't want to render any HTML to avoid pointless traffic. `http.Error`
// should send a minimal response with the appropriate status code.
g_LogErr.Printf("Failed to fetch resource \"%v %v\" to \"%v\": (%v) %v",
Context.Request.Method, Context.Request.URL.Path, Context.Request.RemoteAddr,
Status, http.StatusText(Status))
http.Error(Context.Writer, "", Status)
}
func HandleResource(Context *THttpRequestContext) {
if len(Context.Params) == 0 {
ResourceError(Context, http.StatusNotFound)
return
}
FileName := path.Join(Context.Params...)
File, Err := os.OpenInRoot("./res", FileName)
if Err != nil {
g_LogErr.Printf("Failed to open file (%v): %v", FileName, Err)
ResourceError(Context, http.StatusNotFound)
return
}
defer File.Close()
Stat, Err := File.Stat()
if Err != nil {
g_LogErr.Printf("Failed to retrieve file description (%v): %v", FileName, Err)
ResourceError(Context, http.StatusInternalServerError)
return
}
// NOTE(fusion): File headers.
switch path.Ext(FileName) {
case ".css":
Context.Writer.Header().Set("Content-Type", "text/css")
case ".jpg", ".jpeg":
Context.Writer.Header().Set("Content-Type", "image/jpeg")
case ".js":
Context.Writer.Header().Set("Content-Type", "text/javascript")
case ".png":
Context.Writer.Header().Set("Content-Type", "image/png")
default:
Context.Writer.Header().Set("Content-Disposition",
fmt.Sprintf("attachment; filename=\"%v\"", FileName))
Context.Writer.Header().Set("Content-Type", "application/octet-stream")
}
Context.Writer.Header().Set("Content-Length", strconv.FormatInt(Stat.Size(), 10))
Context.Writer.Header().Set("Date", time.Now().UTC().Format(http.TimeFormat))
Context.Writer.Header().Set("Last-Modified", Stat.ModTime().UTC().Format(http.TimeFormat))
// NOTE(fusion): File contents.
TotalRead := 0
TotalWritten := 0
for {
var Buffer [1024 * 1024]byte
BytesRead, Err := File.Read(Buffer[:])
if Err != nil && Err != io.EOF {
g_LogErr.Printf("Failed to read resource (%v:%v): %v", FileName, TotalRead, Err)
return
}
if BytesRead == 0 {
return
}
BytesWritten, Err := Context.Writer.Write(Buffer[:BytesRead])
if Err != nil || BytesWritten != BytesRead {
g_LogErr.Printf("Failed to write resource (%v:%v): %v", FileName, TotalWritten, Err)
return
}
TotalRead += BytesRead
TotalWritten += BytesWritten
}
}
func HandleFavicon(Context *THttpRequestContext) {
if len(Context.Params) != 0 {
ResourceError(Context, http.StatusNotFound)
return
}
Context.Params = []string{"favicon.ico"}
HandleResource(Context)
}
func HandleIndex(Context *THttpRequestContext) {
Redirect(Context, "/account")
}
func HandleAccount(Context *THttpRequestContext) {
if Context.AccountID > 0 {
RenderAccountSummary(Context)
return
}
switch Context.Request.Method {
case http.MethodGet:
RenderAccountLogin(Context)
case http.MethodPost:
Account := Context.Request.FormValue("account")
Password := Context.Request.FormValue("password")
// TODO(fusion): Other input checks?
if Account == "" || Password == "" {
RenderMessage(Context, "Login Error", "Account or password is not correct.")
return
}
AccountID, Err := strconv.Atoi(Account)
if Err != nil {
g_LogErr.Printf("Failed to parse account id: %d", Err)
RenderMessage(Context, "Login Error", "Account or password is not correct.")
return
}
Result := CheckAccountPassword(AccountID, Password, Context.IPAddress)
switch Result {
case 0:
// NOTE(fusion): Invalidate account's cached data just in case.
InvalidateAccountCachedData(AccountID)
SessionStart(Context, AccountID)
RenderAccountSummary(Context)
case 1, 2:
RenderMessage(Context, "Login Error", "Account or password is not correct.")
case 3:
RenderMessage(Context, "Login Error", "Account disabled for five minutes.")
case 4:
RenderMessage(Context, "Login Error", "IP address blocked for 30 minutes.")
case 5:
RenderMessage(Context, "Login Error", "Your account is banished.")
case 6:
RenderMessage(Context, "Login Error", "Your IP address is banished.")
default:
RenderMessage(Context, "Login Error", "Internal error.")
}
default:
NotFound(Context)
}
}
func HandleAccountLogout(Context *THttpRequestContext) {
SessionEnd(Context)
Redirect(Context, "/account")
}
func HandleAccountCreate(Context *THttpRequestContext) {
if Context.AccountID > 0 {
Redirect(Context, "/account")
return
}
switch Context.Request.Method {
case http.MethodGet:
RenderAccountCreate(Context)
case http.MethodPost:
Account := Context.Request.FormValue("account")
Email := Context.Request.FormValue("email")
Password := Context.Request.FormValue("password")
if Account == "" || Email == "" || Password == "" {
RenderMessage(Context, "Create Account Error", "All inputs are REQUIRED.")
return
}
AccountID, Err := strconv.Atoi(Account)
if Err != nil {
g_LogErr.Printf("Failed to parse account id: %d", Err)
RenderMessage(Context, "Create Account Error", "Invalid account number.")
return
}
if Email != Context.Request.FormValue("email_confirm") {
RenderMessage(Context, "Create Account Error", "Emails don't match.")
return
}
if Password != Context.Request.FormValue("password_confirm") {
RenderMessage(Context, "Create Account Error", "Passwords don't match.")
return
}
if AccountID < 100000 || AccountID > 999999999 {
RenderMessage(Context, "Create Account Error", "Account number must contain 6-9 digits.")
return
}
// TODO(fusion): Proper email and password checking.
if len(Password) < 8 {
RenderMessage(Context, "Create Account Error", "Password must contain at least 8 characters.")
return
}
Result := CreateAccount(AccountID, Email, Password)
switch Result {
case 0:
RenderMessage(Context, "Account Created",
"Your account has been created. Head back to the login page to access it.")
case 1:
RenderMessage(Context, "Create Account Error", "An account with that number already exists.")
case 2:
RenderMessage(Context, "Create Account Error", "An account with that email already exists.")
default:
RenderMessage(Context, "Create Account Error", "Internal error.")
}
default:
NotFound(Context)
}
}
func HandleAccountRecover(Context *THttpRequestContext) {
if Context.AccountID > 0 {
Redirect(Context, "/account")
return
}
switch Context.Request.Method {
case http.MethodGet:
RenderAccountRecover(Context)
default:
NotFound(Context)
}
}
func HandleCharacterCreate(Context *THttpRequestContext) {
if Context.AccountID <= 0 {
Redirect(Context, "/account")
return
}
switch Context.Request.Method {
case http.MethodGet:
RenderCharacterCreate(Context)
case http.MethodPost:
World := strings.TrimSpace(Context.Request.FormValue("world"))
if World == "" || GetWorld(World) == nil {
RenderMessage(Context, "Create Character Error", "Invalid world.")
return
}
// TODO(fusion): Proper name checking.
Name := strings.TrimSpace(Context.Request.FormValue("name"))
if len(Name) < 4 || len(Name) > 25 {
RenderMessage(Context, "Create Character Error", "Name must contain between 8 and 25 characters.")
return
}
Sex, Err := strconv.Atoi(Context.Request.FormValue("sex"))
if Err != nil || (Sex != 1 && Sex != 2) {
if Err != nil {
g_LogErr.Printf("Failed to parse character sex: %v", Err)
}
RenderMessage(Context, "Create Character Error", "Invalid sex.")
return
}
Result := CreateCharacter(World, Context.AccountID, Name, Sex)
switch Result {
case 0:
// NOTE(fusion): Invalidate account's cached data so the new character
// is displayed in the account's summary.
InvalidateAccountCachedData(Context.AccountID)
RenderMessage(Context, "Character Created",
fmt.Sprintf("And so, %v was brought into this world. May fortune"+
" favor your blade and guide your steps through the trials ahead.",
Name))
case 1:
RenderMessage(Context, "Create Character Error",
"Weirdly enough, the selected world doesn't exist. What have you been up to?")
case 2:
RenderMessage(Context, "Create Character Error",
"Weirdly enough, your account doesn't exist. What have you been up to?")
case 3:
RenderMessage(Context, "Create Character Error", "A character with that name already exists.")
default:
RenderMessage(Context, "Create Character Error", "Internal error.")
}
default:
NotFound(Context)
}
}
func HandleCharacterProfile(Context *THttpRequestContext) {
QueryValues := Context.Request.URL.Query()
CharacterName := QueryValues.Get("name")
if CharacterName == "" {
RenderCharacterProfile(Context, nil)
} else {
Result, Character := GetCharacterProfile(CharacterName)
switch Result {
case 0:
RenderCharacterProfile(Context, &Character)
case 1:
RenderMessage(Context, "Search Error", "A character with that name doesn't exist.")
default:
RenderMessage(Context, "Search Error", "Internal error.")
}
}
}
func HandleKillStatistics(Context *THttpRequestContext) {
QueryValues := Context.Request.URL.Query()
WorldName := QueryValues.Get("world")
if WorldName == "" || GetWorld(WorldName) == nil {
Redirect(Context, "/world")
} else {
RenderKillStatistics(Context, WorldName)
}
}
func HandleWorld(Context *THttpRequestContext) {
QueryValues := Context.Request.URL.Query()
WorldName := QueryValues.Get("name")
if WorldName == "" || GetWorld(WorldName) == nil {
RenderWorldList(Context)
} else {
RenderWorldInfo(Context, WorldName)
}
}
func main() {
g_Log.Print("Tibia Web Server v0.2")
if !ReadConfig("config.cfg", WebKVCallback) {
return
}
defer ExitQuery()
defer ExitMail()
defer ExitTemplates()
if !InitQuery() || !InitMail() || !InitTemplates() {
return
}
Router := THttpRouter{}
Router.Add("GET", "/res/", HandleResource)
Router.Add("GET", "/favicon.ico", HandleFavicon)
Router.Add("GET", "/", HandleIndex)
Router.Add("GET", "/index", HandleIndex)
Router.Add("GET", "/account", HandleAccount)
Router.Add("POST", "/account", HandleAccount)
Router.Add("GET", "/account/logout", HandleAccountLogout)
Router.Add("GET", "/account/create", HandleAccountCreate)
Router.Add("POST", "/account/create", HandleAccountCreate)
Router.Add("GET", "/account/recover", HandleAccountRecover)
Router.Add("POST", "/account/recover", HandleAccountRecover)
Router.Add("GET", "/character/create", HandleCharacterCreate)
Router.Add("POST", "/character/create", HandleCharacterCreate)
Router.Add("GET", "/character", HandleCharacterProfile)
Router.Add("GET", "/killstatistics", HandleKillStatistics)
Router.Add("GET", "/world", HandleWorld)
Router.NotFound = NotFound
// NOTE(fusion): Force the server to run on IPv4 because that is the only
// format the query manager currently handles. Trying to use IPv6 will cause
// queries to fail.
if FileExists(g_HttpsCertFile) && FileExists(g_HttpsKeyFile) {
Listener, Err := net.Listen("tcp4", JoinHostPort("", g_HttpsPort))
if Err != nil {
g_LogErr.Printf("Failed to listen to HTTPS port %v: %v", g_HttpsPort, Err)
return
}
g_Log.Printf("Running over HTTPS on port %v", g_HttpsPort)
g_Log.Print(http.ServeTLS(Listener, &Router, g_HttpsCertFile, g_HttpsKeyFile))
} else {
g_LogWarn.Print("The server is setup to run over HTTP which is NOT SECURE" +
" and prone to a man-in-the-middle or eavesdropping attack. This setup" +
" may only be used for TESTING.")
Listener, Err := net.Listen("tcp4", JoinHostPort("", g_HttpPort))
if Err != nil {
g_LogErr.Printf("Failed to listen to HTTP port %v: %v", g_HttpPort, Err)
return
}
g_Log.Printf("Running over HTTP on port %v", g_HttpPort)
g_Log.Print(http.Serve(Listener, &Router))
}
}