-
Notifications
You must be signed in to change notification settings - Fork 19
/
install.go
754 lines (639 loc) · 19.4 KB
/
install.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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
package main
import (
"errors"
"html/template"
"net"
"net/http"
"os"
"strconv"
"time"
"github.com/dchest/uniuri"
"github.com/julienschmidt/httprouter"
"github.com/urfave/negroni"
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
"github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx"
"github.com/raggaer/castro/app/database"
"github.com/raggaer/castro/app/lua"
"github.com/raggaer/castro/app/models"
"github.com/raggaer/castro/app/util"
glua "github.com/yuin/gopher-lua"
)
const (
// configFileName the name of the application configuration file
configFileName = "config.toml"
// znoteTableName name of the znote table
znoteTableName = "znote"
)
var (
installationSteps = []installationStep{
{
Name: "Path",
URL: "/",
Description: template.HTML(`
<p>Welcome to the installation wizard. The wizard will guide you through a very simple process where you will be able to setup some Castro features like the SMTP server and the Google reCAPTCHA service</p>
<p>These features are optional and you can activate them later</p>
<p>Just fill the information below to start using one of the most powerful and extensible Open Tibia content management system</p>
`),
Optional: false,
Form: []installationFormField{
{
Name: "path",
Type: "text",
Placeholder: "Server full path",
HelperText: "We need your full server folder path. Castro will load all the necessary information from your config.lua file",
},
{
Name: "port",
Type: "number",
Placeholder: "Website port",
HelperText: "Port where Castro will listen. You should use port 80 unless you run Castro behind a proxy server like NGINX or Caddy",
},
{
Name: "url",
Type: "text",
Placeholder: "Website url",
HelperText: "Your absolute website URL. This URL will be used to create links. URL/destination",
},
{
Name: "map",
IsSelect: true,
SelectOptions: []installationSelectOption{
{
Name: "map",
Value: "Load from map",
},
{
Name: "config",
Value: "Load from config",
},
},
HelperText: `Load towns from the .otbm map file. If for some reason your map is not compatible use the option 'Load from config'.
You will need to fill the Map house file field and populate your town list`,
},
{
Name: "housefile",
Type: "text",
Placeholder: "Map house file. Only fill this field if you use 'Load from config' map option",
HelperText: "Map house file name. Only fill this field if you use 'Load from config' map option",
},
{
Name: "towns",
IsTextArea: true,
HelperText: "List of map towns. Using the following format: Town id - Town name. Only fill this field if you use 'Load from config' map option",
},
},
Post: func(res http.ResponseWriter, req *http.Request, s installationStep) error {
// Get server port
port, err := strconv.Atoi(req.FormValue("port"))
if err != nil {
return errors.New("Invalid port number")
}
// Set load map settings
installationConfigFile.LoadMap = req.FormValue("map") == "Load from map"
installationConfigFile.MapWatch.Enabled = req.FormValue("map") == "Load from map"
installationConfigFile.MapHouseFile = req.FormValue("housefile")
// Install database tables
if err := installApplication(req.FormValue("path")); err != nil {
return err
}
// Set application settings
installationConfigFile.Datapack = req.FormValue("path")
installationConfigFile.Port = port
installationConfigFile.URL = req.FormValue("url")
if installationConfigFile.LoadMap {
return nil
}
// Parse textarea towns
towns := strings.Split(req.FormValue("towns"), "\r\n")
for _, town := range towns {
townData := strings.Split(strings.TrimSpace(town), "-")
if len(townData) < 2 {
continue
}
townID, err := strconv.ParseUint(strings.TrimSpace(townData[0]), 10, 32)
if err != nil {
return err
}
installationConfigFile.Towns = append(installationConfigFile.Towns, util.ConfigTown{
Name: strings.TrimSpace(townData[1]),
ID: uint32(townID),
})
}
return nil
},
},
{
Name: "Captcha",
URL: "/install/captcha",
Optional: true,
Description: template.HTML(`
<p>You can configure your Google reCAPTCHA credentials. reCAPTCHA offers an easy way to stop bots at saturaing your database</p>
<p>By default if captcha is enabled it will appear on the registration form, you can use lua bindings to add captcha security to any other form of the website</p>
<p>To setup your captcha service head to <a href="https://www.google.com/recaptcha/admin#list">Google reCAPTCHA</a> and create a new application, make sure to select <b>reCAPTCHA v2</b> as your application type. You can also learn how to integreate captchas on Castro by heading to the <a href="https://docs.castroaac.org/docs/lua/captcha">documentation page</a></p>
`),
Form: []installationFormField{
{
Name: "public",
Type: "text",
Placeholder: "Captcha public key",
HelperText: "Google reCAPTCHA public key",
},
{
Name: "private",
Type: "text",
Placeholder: "Captcha private key",
HelperText: "Google reCAPTCHA private key",
},
},
Post: func(res http.ResponseWriter, req *http.Request, s installationStep) error {
// Update fields
installationConfigFile.Captcha = util.CaptchaConfig{
Public: req.FormValue("public"),
Secret: req.FormValue("private"),
Enabled: true,
}
return nil
},
},
{
Name: "Mail",
URL: "/install/mail",
Optional: true,
Description: template.HTML(`
<p>You can configure an SMTP server to send emails within Castro. Please fill the form below</p>
<p>If you want to read more about sending emails using Castro lua bindings head to the <a href="https://docs.castroaac.org/docs/lua/mail">documentation page</a></p>
`),
Form: []installationFormField{
{
Name: "server",
Type: "text",
Placeholder: "SMTP server address",
HelperText: "Address of your SMTP server",
},
{
Name: "port",
Type: "number",
Placeholder: "SMTP server port",
HelperText: "Port where your SMTP server listens on",
},
{
Name: "username",
Type: "text",
Placeholder: "SMTP server username",
HelperText: "Login username for your SMTP server",
},
{
Name: "password",
Type: "password",
Placeholder: "SMTP server password",
HelperText: "Login password for your SMTP server",
},
},
Post: func(res http.ResponseWriter, req *http.Request, s installationStep) error {
// Get server port
port, err := strconv.Atoi(req.FormValue("port"))
if err != nil {
return err
}
// Update fields
installationConfigFile.Mail = util.MailConfig{
Server: req.FormValue("server"),
Port: port,
Username: req.FormValue("username"),
Password: req.FormValue("password"),
}
return nil
},
},
}
// Installation template holder
installationTemplate = template.New("install")
// Installation config file holder
installationConfigFile = &util.Configuration{
CheckUpdates: true,
LoadMap: true,
Template: "views/default",
Mode: "dev",
Port: 80,
URL: "localhost",
Datapack: "",
Static: util.StaticConfig{
Enabled: true,
Directory: "public/",
},
Plugin: util.PluginConfig{
Enabled: true,
Origin: "https://plugins.castroaac.org",
},
MapWatch: util.MapWatchConfig{
Enabled: true,
Check: util.NewStringDuration("1h"),
},
Cookies: util.CookieConfig{
Name: fmt.Sprintf("castro-%v", uniuri.NewLen(5)),
MaxAge: 1000000,
HashKey: uniuri.NewLen(32),
BlockKey: uniuri.NewLen(32),
},
Cache: util.CacheConfig{
Default: util.NewStringDuration("5m"),
Purge: util.NewStringDuration("1m"),
},
RateLimit: util.RateLimiterConfig{
Number: 100,
Enabled: false,
Time: util.NewStringDuration("1m"),
},
Security: util.SecurityConfig{
NonceEnabled: true,
STS: "max-age=10000",
XSS: "1; mode=block",
Frame: "DENY",
ContentType: "nosniff",
ReferrerPolicy: "origin",
CrossDomainPolicy: "none",
CSP: util.ContentSecurityPolicyConfig{
Default: []string{"none"},
Frame: util.ContentSecurityPolicyType{
SRC: []string{"http://pay.fortumo.com", "https://www.google.com"},
},
Script: util.ContentSecurityPolicyType{
Default: []string{"self"},
SRC: []string{"https://stackpath.bootstrapcdn.com", "https://ajax.googleapis.com", "https://assets.fortumo.com", "https://www.google.com", "https://code.jquery.com", "https://cdn.datatables.net", "https://www.gstatic.com"},
},
Font: util.ContentSecurityPolicyType{
Default: []string{"self"},
SRC: []string{"https://use.fontawesome.com", "http://fonts.gstatic.com", "http://fonts.googleapis.com"},
},
Connect: util.ContentSecurityPolicyType{
Default: []string{"self"},
},
Style: util.ContentSecurityPolicyType{
Default: []string{"unsafe-inline", "self"},
SRC: []string{"https://use.fontawesome.com", "https://stackpath.bootstrapcdn.com", "https://assets.fortumo.com", "http://fonts.googleapis.com", "https://cdn.datatables.net"},
},
Image: util.ContentSecurityPolicyType{
Default: []string{"self"},
SRC: []string{"https://assets.fortumo.com", "https://*.githubusercontent.com", "data:"},
},
},
},
}
)
// znoteTable main znote installation table to look for
type znoteTable struct {
Version int
Installed int64
}
// znoteAccount main znote accounts table
type znoteAccount struct {
ID uint64
Account_id int64
Points uint
}
type installationStep struct {
URL string
Optional bool
Description template.HTML
Name string
Form []installationFormField
Post installationFormHandle
}
type installationFormHandle func(http.ResponseWriter, *http.Request, installationStep) error
type installationTemplateData struct {
Step installationStep
Success string
Error string
Next string
Last bool
Sidebar []installationStep
}
type installationFormField struct {
Name string
Type string
Placeholder string
HelperText string
IsSelect bool
IsTextArea bool
SelectOptions []installationSelectOption
}
type installationSelectOption struct {
Name string
Value string
}
// isInstalled check if application is installed
func isInstalled() bool {
// Check if file exists
_, err := os.Stat(configFileName)
return err == nil
}
// isZnoteInstalled checks if znote_aac is already installed
func isZnoteInstalled(db *sqlx.Tx) (bool, error) {
// Check if table exists
if _, err := db.Exec("DESCRIBE " + znoteTableName); err != nil {
// Convert error to MySQL error type
mErr, ok := err.(*mysql.MySQLError)
// Check if table is installed
if ok && mErr.Number == 1146 {
return false, nil
}
return false, err
}
return true, nil
}
func accountExists(id int64, db *sqlx.Tx) bool {
// Data holder
exists := false
// Check if account exists
if err := db.Get(&exists, "SELECT EXISTS (SELECT 1 FROM castro_accounts WHERE account_id = ?)", id); err != nil {
return false
}
return exists
}
// startInstallerApplication starts the installer server and the installer template
func startInstallerApplication() error {
// Register html files
if err := registerInstallationTemplate(); err != nil {
return err
}
// Create installer router
router := httprouter.New()
router.GET("/install/finish", showInstallationFinish)
router.POST("/install/finish", installationFinish)
// Loop installation steps
for i, step := range installationSteps {
// Register get route
router.GET(step.URL, installationStepGet(i, step))
// Register post route
router.POST(step.URL, installationStepPost(i, step))
}
// Create installer listener
listener, err := net.Listen("tcp", ":8080")
if err != nil {
return err
}
// Create negroni middleware
n := negroni.New(
negroni.NewStatic(http.Dir("public/")),
)
// Use httprouter router
n.UseHandler(router)
fmt.Println("Castro is not installed. Installer will listen on " + listener.Addr().String())
// Start installer http server
return http.Serve(listener, n)
}
func installationStepPost(i int, step installationStep) httprouter.Handle {
// Set template data
d := &installationTemplateData{
Error: "",
Success: "",
Step: step,
Next: "",
Sidebar: installationSteps,
}
// Return httprouter handle
return func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
// Parse form
if err := req.ParseForm(); err != nil {
d.Error = err.Error()
installationTemplate.ExecuteTemplate(res, "install.html", d)
return
}
// Call form parser
if err := step.Post(res, req, step); err != nil {
d.Error = err.Error()
installationTemplate.ExecuteTemplate(res, "install.html", d)
return
}
// Check if there is next step
if i+1 >= len(installationSteps) {
// Redirect to final page
http.Redirect(res, req, "/install/finish", 302)
return
}
// Redirect to next step
http.Redirect(res, req, installationSteps[i+1].URL, 302)
}
}
func installationStepGet(i int, step installationStep) httprouter.Handle {
// Set template data
d := &installationTemplateData{
Error: "",
Success: "",
Step: step,
Next: "",
Last: false,
Sidebar: installationSteps,
}
// Check if step is optional
if step.Optional {
// Check if there are more steps
if i+1 < len(installationSteps) {
d.Next = installationSteps[i+1].URL
}
}
if i+1 >= len(installationSteps) {
d.Last = true
}
// Return httprouter handle
return func(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
// Execute step template
installationTemplate.ExecuteTemplate(res, "install.html", d)
}
}
func installationFinish(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
// Create config file
if err := createConfigFile("config.toml", installationConfigFile); err != nil {
installationTemplate.ExecuteTemplate(res, "install_encode.html", installationTemplateData{
Error: err.Error(),
})
return
}
// Render finish template
installationTemplate.ExecuteTemplate(res, "install_finish.html", nil)
}
func showInstallationFinish(res http.ResponseWriter, req *http.Request, params httprouter.Params) {
// Execute encode layout
installationTemplate.ExecuteTemplate(res, "install_encode.html", nil)
}
// registerInstallationTemplate register the html template files
func registerInstallationTemplate() error {
// Parse installation html files
_, err := installationTemplate.ParseGlob(filepath.Join("views", "install", "*.html"))
return err
}
// installApplication runs the installation process
func installApplication(location string) error {
// Load config.lua file
if err := lua.LoadConfig(
filepath.Join(filepath.Join(location, "config.lua")),
); err != nil {
return err
}
// Connect to database
conn, err := database.Open(lua.Config.GetGlobal("mysqlUser").String(),
lua.Config.GetGlobal("mysqlPass").String(),
lua.Config.GetGlobal("mysqlHost").String(),
lua.Config.GetGlobal("mysqlPort").String(),
lua.Config.GetGlobal("mysqlDatabase").String(),
"&multiStatements=true",
)
if err != nil {
return err
}
// Set global handler for lua states
database.DB = conn
// Ping database
if err := database.DB.Ping(); err != nil {
return err
}
// Close database handle
defer database.DB.Close()
// Begin transaction
db, err := database.DB.Beginx()
if err != nil {
db.Rollback()
return err
}
// Get all sql files
tables, err := ioutil.ReadDir(filepath.Join("install"))
if err != nil {
db.Rollback()
return err
}
// Loop files
for _, table := range tables {
// Check if table exists
if _, err := db.Exec("DESCRIBE " + strings.TrimSuffix(table.Name(), ".sql")); err != nil {
// Convert error to MySQL error type
mErr, ok := err.(*mysql.MySQLError)
// Check if table is installed
if ok && mErr.Number == 1146 {
// Read file
buff, err := ioutil.ReadFile(filepath.Join("install", table.Name()))
if err != nil {
db.Rollback()
return err
}
// Execute query
if _, err := db.Exec(string(buff)); err != nil {
db.Rollback()
return err
}
continue
}
return err
}
}
// Check if znote is installed
z, err := isZnoteInstalled(db)
if err != nil {
db.Rollback()
return err
}
if z {
// Znote accounts placeholder
znoteAccounts := []znoteAccount{}
// Get znote accounts
if err := db.Select(&znoteAccounts, "SELECT id, account_id, points FROM znote_accounts ORDER BY id"); err != nil {
db.Rollback()
return err
}
// Loop znote accounts
for _, acc := range znoteAccounts {
// Check if account exists
if accountExists(acc.Account_id, db) {
continue
}
// Insert castro account from znote account
if _, err := db.Exec("INSERT INTO castro_accounts (account_id, points) VALUES (?, ?)", acc.Account_id, acc.Points); err != nil {
db.Rollback()
return err
}
}
}
// Normal accounts placeholder
accountList := []models.Account{}
// Get all accounts
if err := db.Select(&accountList, "SELECT id FROM accounts ORDER BY id"); err != nil {
db.Rollback()
return err
}
// Loop accounts
for _, acc := range accountList {
// Check if account exists
if accountExists(acc.ID, db) {
continue
}
// Insert castro account from normal account
if _, err := db.Exec("INSERT INTO castro_accounts (account_id) VALUES (?)", acc.ID); err != nil {
db.Rollback()
return err
}
}
if installationConfigFile.LoadMap {
fmt.Print(">> Encoding map file. This process can take several minutes")
// Encode server map
mapData, err := util.EncodeMap(
filepath.Join(location, "data", "world", lua.Config.GetGlobal("mapName").String()+".otbm"),
)
if err != nil {
db.Rollback()
return err
}
fmt.Println(" (done)")
// Get map modtime
mapStat, err := os.Stat(filepath.Join(location, "data", "world", lua.Config.GetGlobal("mapName").String()+".otbm"))
if err != nil {
db.Rollback()
return err
}
// Save encoded map
if _, err := db.Exec(
"INSERT INTO castro_map (name, data, created_at, updated_at, last_modtime) VALUES (?, ?, ?, ?, ?)",
lua.Config.GetGlobal("mapName").String(),
mapData,
time.Now(),
time.Now(),
mapStat.ModTime(),
); err != nil {
db.Rollback()
return err
}
}
// Commit changes
if err := db.Commit(); err != nil {
db.Rollback()
return err
}
return nil
}
// createConfigFile encodes a configuration file with the given name and location
func createConfigFile(name string, cfg *util.Configuration) error {
// Get lua state
luaState := glua.NewState()
// Close state
defer luaState.Close()
// Get application state ready
lua.GetApplicationState(luaState)
// Execute init file
if err := lua.ExecuteFile(luaState, filepath.Join("engine", "install.lua")); err != nil {
return err
}
// Create configuration file handle
configFile, err := os.Create(name)
if err != nil {
return err
}
// Close file handle
defer configFile.Close()
// Get lua file table
cfg.Custom = lua.TableToMap(luaState.ToTable(-1))
// Encode the given configuration struct into the file
return toml.NewEncoder(configFile).Encode(cfg)
}