-
Notifications
You must be signed in to change notification settings - Fork 40
/
main.go
1044 lines (930 loc) · 31.9 KB
/
main.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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
// FIXME: After the API and webui pieces are done, figure out how the DB4S end
// point and dio should be updated to use live databases too
import (
"bytes"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"encoding/json"
"fmt"
"html"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
gz "github.com/NYTimes/gziphandler"
"github.com/pkg/errors"
com "github.com/sqlitebrowser/dbhub.io/common"
"github.com/sqlitebrowser/dbhub.io/common/config"
"github.com/sqlitebrowser/dbhub.io/common/database"
)
var (
// Our self signed Certificate Authority chain
ourCAPool *x509.CertPool
// Address of our server, formatted for display
server string
)
func main() {
// Read server configuration
var err error
if err = config.ReadConfig(); err != nil {
log.Fatalf("Configuration file problem: '%s'", err)
}
// Set the node name used in various logging strings
config.Conf.Live.Nodename = "DB4S end point server"
// Set the temp dir environment variable
err = os.Setenv("TMPDIR", config.Conf.DiskCache.Directory)
if err != nil {
log.Fatalf("Setting temp directory environment variable failed: '%s'", err)
}
// Connect to Minio server
err = com.ConnectMinio()
if err != nil {
log.Fatal(err)
}
// Connect to database
err = database.Connect()
if err != nil {
log.Fatal(err)
}
// Connect to the Memcached server
err = com.ConnectCache()
if err != nil {
log.Fatal(err)
}
// Start background goroutines to handle job queue responses
com.ResponseQueue = com.NewResponseQueue()
com.CheckResponsesQueue = make(chan struct{})
com.SubmitterInstance = com.RandomString(3)
go com.ResponseQueueCheck()
go com.ResponseQueueListen()
// Start background signal handler
exitSignal := make(chan struct{}, 1)
go com.SignalHandler(&exitSignal)
// Load our self signed CA chain
ourCAPool = x509.NewCertPool()
certFile, err := os.ReadFile(config.Conf.DB4S.CAChain)
if err != nil {
log.Fatalf("Error opening Certificate Authority chain file: '%s'", err)
}
ok := ourCAPool.AppendCertsFromPEM(certFile)
if !ok {
log.Fatal("Error appending certificate file")
}
// URL handler
mux := http.NewServeMux()
mux.HandleFunc("/", rootHandler)
mux.HandleFunc("/branch/list", branchListHandler)
mux.HandleFunc("/licence/add", licenceAddHandler)
mux.HandleFunc("/licence/get", licenceGetHandler)
mux.HandleFunc("/licence/list", licenceListHandler)
mux.HandleFunc("/licence/remove", licenceRemoveHandler)
mux.HandleFunc("/metadata/get", metadataGetHandler)
// Load our self signed CA Cert chain, request client certificates, and set TLS1.2 as minimum
newTLSConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: ourCAPool,
MinVersion: tls.VersionTLS12,
PreferServerCipherSuites: true,
RootCAs: ourCAPool,
}
newServer := &http.Server{
Addr: ":" + fmt.Sprint(config.Conf.DB4S.Port),
ErrorLog: com.HttpErrorLog(),
Handler: gz.GzipHandler(mux),
TLSConfig: newTLSConfig,
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
}
// Generate the formatted server string
if config.Conf.DB4S.Port == 443 {
server = fmt.Sprintf("https://%s", config.Conf.DB4S.Server)
} else {
server = fmt.Sprintf("https://%s:%d", config.Conf.DB4S.Server, config.Conf.DB4S.Port)
}
// Start server
log.Printf("%s: listening for requests on %s", config.Conf.Live.Nodename, server)
go newServer.ListenAndServeTLS(config.Conf.DB4S.Certificate, config.Conf.DB4S.CertificateKey)
// Wait for exit signal
<-exitSignal
}
// Returns the list of branches for a database
func branchListHandler(w http.ResponseWriter, r *http.Request) {
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Extract and validate the form variables
dbOwner, _, dbName, err := com.GetUFD(r, true)
if err != nil {
http.Error(w, "Missing or incorrect data supplied", http.StatusBadRequest)
return
}
// Check if the requested database exists
exists, err := database.CheckDBPermissions(userAcc, dbOwner, dbName, false)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !exists {
fmt.Fprint(w, "{}")
return
}
// Retrieve the branch list for the database
brList, err := com.BranchListResponse(dbOwner, dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Return the list as JSON
jsonList, err := json.MarshalIndent(brList, "", " ")
if err != nil {
errMsg := fmt.Sprintf("Error when JSON marshalling the branch list: %v", err)
log.Print(errMsg)
http.Error(w, errMsg, http.StatusBadRequest)
return
}
fmt.Fprintf(w, string(jsonList))
return
}
func extractUserAndServer(w http.ResponseWriter, r *http.Request) (userAcc string, certServer string, err error) {
// Extract the account name and associated server from the validated client certificate
cn := r.TLS.PeerCertificates[0].Subject.CommonName
if cn == "" {
// Common name is empty
err = errors.New("Common name is blank in client certificate")
return
}
s := strings.Split(cn, "@")
if len(s) < 2 {
err = errors.New("Missing information in client certificate")
return
}
userAcc = s[0]
certServer = s[1]
if userAcc == "" || certServer == "" {
// Missing details in common name field
err = errors.New("Missing information in client certificate")
return
}
// Verify the running server matches the one in the certificate
runningServer := config.Conf.DB4S.Server
if certServer != runningServer {
err = fmt.Errorf("Server name in certificate '%s' doesn't match running server '%s'\n", certServer,
runningServer)
return
}
// Everything is ok, so return
return
}
func generateDefaultList(pageName string, userAcc string) (defaultList []byte, err error) {
pageName += ":generateDefaultList()"
// Retrieve the list of most recently modified (available) databases
var userList com.UserInfoSlice
userList, err = com.DB4SDefaultList(userAcc)
if err != nil {
// Return an empty set
return []byte{'[', ']'}, err
}
// Ready the data for JSON Marshalling
type linkRow struct {
Type string `json:"type"`
Name string `json:"name"`
URL string `json:"url"`
LastModified string `json:"last_modified"`
}
var linkRows []linkRow
var rowCount int
for _, j := range userList {
newLink := linkRow{
Type: "folder",
Name: j.Username,
URL: server + "/" + j.Username,
LastModified: j.LastModified.Format(time.RFC3339)}
linkRows = append(linkRows, newLink)
rowCount++
}
if rowCount > 0 {
// Use json.MarshalIndent() for nicer looking output
defaultList, err = json.MarshalIndent(linkRows, "", " ")
if err != nil {
log.Printf("%s: Error when JSON marshalling the default list: %v", pageName, err)
return nil, errors.Wrap(err, fmt.Sprintf("%s: Error when JSON marshalling the default list",
pageName))
}
} else {
// Return an empty set indicator, instead of "null"
defaultList = []byte{'[', ']'}
}
return defaultList, nil
}
func getHandler(w http.ResponseWriter, r *http.Request, userAcc string) {
pageName := "GET request handler"
// Split the request URL into path components
pathStrings := strings.Split(r.URL.Path, "/")
// numPieces will be 2 if the request was for the root directory (https://server/), or if
// the request included only a single path component (https://server/someuser/)
numPieces := len(pathStrings)
if numPieces == 2 {
// Check if the request was for the root directory
if pathStrings[1] == "" {
// Yep, root directory request. Log it and generate the browse list
var userAgent string
ua, ok := r.Header["User-Agent"]
if ok {
userAgent = ua[0]
}
if err := database.LogDB4SConnect(userAcc, r.RemoteAddr, userAgent, time.Now().UTC()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Generate the list of potential user directories for browsing
defaultList, err := generateDefaultList(pageName, userAcc)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", defaultList)
return
}
// The request was for a user directory, so return that list
desiredUserDir := pathStrings[1]
err := com.ValidateUser(desiredUserDir)
if err != nil {
log.Printf("db4s: Validation failed for username: %s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dbList, err := userDatabaseList(userAcc, desiredUserDir)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", dbList)
return
}
// This catches the case where a "/" is on the end of the URL
// TODO: Refactor this and the above identical code. Doing it this way is non-optimal
if pathStrings[2] == "" {
// The request was for a user directory, so return that list
desiredUserDir := pathStrings[1]
err := com.ValidateUser(desiredUserDir)
if err != nil {
log.Printf("db4s: Validation failed for username: %s", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dbList, err := userDatabaseList(userAcc, desiredUserDir)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "%s", dbList)
return
}
// Use easily understandable variable names
dbOwner := pathStrings[1]
dbName := pathStrings[2]
// Validate the dbOwner and dbName inputs
err := com.ValidateUser(dbOwner)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = com.ValidateDB(dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Check if the requested database exists
exists, err := database.CheckDBPermissions(userAcc, dbOwner, dbName, false)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !exists {
http.Error(w, fmt.Sprintf("Database '%s/%s' doesn't exist", com.SanitiseLogString(dbOwner),
com.SanitiseLogString(dbName)), http.StatusNotFound)
return
}
// Extract the requested database commit id from the form data
commit, err := com.GetFormCommit(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get the branch heads list for the database
branchList, err := database.GetBranches(dbOwner, dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// If a branch name was provided use it, else use the default branch for the database
var branchName string
bn, err := com.GetFormBranch(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if bn != "" {
_, ok := branchList[bn]
if !ok {
http.Error(w, "Unknown branch name", http.StatusNotFound)
return
}
branchName = bn
} else {
// No branch name was given, so retrieve the default for the database
branchName, err = database.GetDefaultBranchName(dbOwner, dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// If no commit ID was given, we use the latest commit in the branch
if commit == "" {
branch, ok := branchList[branchName]
if !ok {
http.Error(w, "Unknown branch name", http.StatusNotFound)
return
}
commit = branch.Commit
}
// Check that the commit is known to the database
commitList, err := database.GetCommitList(dbOwner, dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, ok := commitList[commit]
if !ok {
http.Error(w, "Commit not found", http.StatusNotFound)
return
}
// A specific database was requested, so send it to the user
err = retrieveDatabase(w, r, pageName, userAcc, dbOwner, dbName, branchName, commit)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Adds a new licence to DBHub.io
func licenceAddHandler(w http.ResponseWriter, r *http.Request) {
// Set the maximum accepted size for uploading
r.Body = http.MaxBytesReader(w, r.Body, com.MaxLicenceSize*1024*1024) // 1MB. Seems fairly generous for licence text.
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// The "public" user isn't allowed to make changes
if userAcc == "public" {
log.Printf("User from '%s' attempted to add a licence using the public certificate", r.RemoteAddr)
http.Error(w, "You're using the 'public' certificate, which isn't allowed to make changes on the server",
http.StatusUnauthorized)
return
}
// Check whether the uploaded licence file is too large
if r.ContentLength > (com.MaxLicenceSize * 1024 * 1024) {
http.Error(w,
fmt.Sprintf("Licence file is too large. Maximum licence upload size is %d MB, yours is %d MB",
com.MaxLicenceSize, r.ContentLength/1024/1024), http.StatusBadRequest)
log.Println(fmt.Sprintf("'%s' attempted to upload an oversized licence %d MB in size. Limit is %d MB",
userAcc, r.ContentLength/1024/1024, com.MaxLicenceSize))
return
}
// Make sure a licence ID (short name) was provided
l := r.FormValue("licence_id")
if l == "" {
http.Error(w, "No licence ID supplied", http.StatusBadRequest)
return
}
err = com.ValidateLicence(l)
if err != nil {
log.Printf("Validation failed for licence ID: '%s': %s", com.SanitiseLogString(l), err)
http.Error(w, "Validation of licence ID failed", http.StatusBadRequest)
return
}
licID := l
// If an (optional) full name for the licence was provided, then validate it
var licName string
if z := r.FormValue("licence_name"); z != "" {
err = com.ValidateLicenceFullName(z)
if err != nil {
log.Printf("Validation failed for licence full name: '%s': %s", com.SanitiseLogString(z), err)
http.Error(w, "Validation of licence full name failed", http.StatusBadRequest)
return
}
licName = z
}
// The display order parameter is required
do := r.FormValue("display_order")
dispOrder, err := strconv.Atoi(do)
if err != nil {
http.Error(w, fmt.Sprintf("Invalid display order: %v", html.EscapeString(do)), http.StatusBadRequest)
return
}
// Ensure a licence by the same name (for this user) doesn't already exist, and the supplied display order isn't
// already used
licList, err := database.GetLicences(userAcc)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for i, j := range licList {
if i == licID {
http.Error(w, "A licence with that short name/id already exists", http.StatusConflict)
return
}
if dispOrder == j.Order {
http.Error(w, "That display order number is already used by another licence", http.StatusConflict)
return
}
}
// The file format parameter is required, and can only be "text" or "html"
var fileFormat string
ff := r.FormValue("file_format")
switch ff {
case "text":
fileFormat = "text"
case "html":
fileFormat = "html"
default:
http.Error(w, fmt.Sprintf("Unknown file format: %s", html.EscapeString(ff)), http.StatusBadRequest)
return
}
// If a source URL was provided then validate it
var sourceURL string
su := r.FormValue("source_url")
if su != "" {
err = com.Validate.Var(su, "url,min=5,max=255") // 255 seems like a reasonable first guess
if err != nil {
http.Error(w, "Validation failed for source URL value", http.StatusBadRequest)
return
}
sourceURL = su
}
// Grab the uploaded file and form variables
tempFile, _, err := r.FormFile("file1")
if err != nil {
log.Printf("Uploading licence failed: %v", err)
http.Error(w, fmt.Sprintf("Something went wrong when extracting the licence text: '%s'", err.Error()),
http.StatusBadRequest)
return
}
defer tempFile.Close()
// Just use an in-memory buffer for the licence text
licText := new(bytes.Buffer)
_, err = io.Copy(licText, tempFile)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Make sure this licence isn't a duplicate of an existing one
tmpSHA := sha256.Sum256(licText.Bytes())
licSHA := hex.EncodeToString(tmpSHA[:])
licCheckName, licCheckURL, err := database.GetLicenceInfoFromSha256(userAcc, string(licSHA[:]))
if err != nil && err.Error() != "No matching licence found, something has gone wrong!" {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if licCheckName != "" || licCheckURL != "" {
http.Error(w, fmt.Sprintf("This licence is already in the system, using the short name of '%s'",
licCheckName), http.StatusConflict)
return
}
// Save the licence in the database
err = database.StoreLicence(userAcc, licID, licText.Bytes(), sourceURL, dispOrder, licName, fileFormat)
if err != nil {
http.Error(w, fmt.Sprintf("Something went wrong when storing the new licence file: '%s'", err.Error()),
http.StatusInternalServerError)
return
}
// Send a success message back to the client
w.WriteHeader(http.StatusCreated)
_, _ = fmt.Fprintf(w, "Success")
// Log the new licence addition
log.Printf("New licence '%s' added to the server by user '%v'", com.SanitiseLogString(licID), userAcc)
return
}
// Returns the text or html document for a specific licence
func licenceGetHandler(w http.ResponseWriter, r *http.Request) {
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Make sure a licence name was provided
l := r.FormValue("licence")
if l == "" {
http.Error(w, "No licence name supplied", http.StatusBadRequest)
return
}
// Validate the licence name
err = com.ValidateLicence(l)
if err != nil {
log.Printf("Validation failed for licence name: '%s': %s", com.SanitiseLogString(l), err)
http.Error(w, "Validation of licence name failed", http.StatusBadRequest)
return
}
licenceName := l
// Retrieve the licence from our database
lic, format, err := database.GetLicence(userAcc, licenceName)
if err != nil {
if err.Error() == "unknown licence" {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Determine file extension and mime type
var fileExt, mimeType string
switch format {
case "text":
fileExt = "txt"
mimeType = "text/plain"
case "html":
fileExt = "html"
mimeType = "text/html"
default:
// Unknown licence file format
http.Error(w, fmt.Sprintf("Unknown licence format '%s'", format), http.StatusInternalServerError)
return
}
// Send the licence file to the user
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s",
url.QueryEscape(licenceName+"."+fileExt)))
w.Header().Set("Content-Type", mimeType)
bytesWritten, err := fmt.Fprint(w, lic)
if err != nil {
log.Printf("Error returning licence file: %v", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Log the transfer
log.Printf("Licence '%s' downloaded by user '%v', %d bytes", com.SanitiseLogString(licenceName), userAcc, bytesWritten)
return
}
// Returns the list of licences known to the server
func licenceListHandler(w http.ResponseWriter, r *http.Request) {
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Return the list of licences as JSON
licList, err := database.GetLicences(userAcc)
jsonLicList, err := json.MarshalIndent(licList, "", " ")
if err != nil {
errMsg := fmt.Sprintf("Error when JSON marshalling the licence list: %v", err)
log.Print(errMsg)
http.Error(w, errMsg, http.StatusBadRequest)
return
}
fmt.Fprintf(w, string(jsonLicList))
return
}
// Removes a (user added) licence from the system
func licenceRemoveHandler(w http.ResponseWriter, r *http.Request) {
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// The "public" user isn't allowed to make changes
if userAcc == "public" {
log.Printf("User from '%s' attempted to remove a licence using the public certificate", r.RemoteAddr)
http.Error(w, "You're using the 'public' certificate, which isn't allowed to make changes on the server",
http.StatusUnauthorized)
return
}
// Make sure a licence short name was provided
l := r.FormValue("licence_id")
if l == "" {
http.Error(w, "No licence name supplied", http.StatusBadRequest)
return
}
// Validate the licence name
err = com.ValidateLicence(l)
if err != nil {
log.Printf("Validation failed for licence name: '%s': %s", com.SanitiseLogString(l), err)
http.Error(w, "Validation of licence name failed", http.StatusBadRequest)
return
}
licenceName := l
// Check if the licence to be deleted is in the system
exists, err := database.CheckLicenceExists(userAcc, licenceName)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !exists {
http.Error(w, "A user supplied licence with that short name can't be found", http.StatusNotFound)
return
}
// Remove the licence from our database
err = database.DeleteLicence(userAcc, licenceName)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Send a success message back to the client
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Success")
// Log the transfer
log.Printf("Licence '%s' removed by user '%v'", com.SanitiseLogString(licenceName), userAcc)
return
}
// Returns the JSON metadata for a specific database
func metadataGetHandler(w http.ResponseWriter, r *http.Request) {
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Extract and validate the form variables
dbOwner, _, dbName, err := com.GetUFD(r, true)
if err != nil {
http.Error(w, "Missing or incorrect data supplied", http.StatusBadRequest)
return
}
// Check if the requested database exists
exists, err := database.CheckDBPermissions(userAcc, dbOwner, dbName, false)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !exists {
http.Error(w, fmt.Sprintf("Database '%s/%s' doesn't exist", dbOwner, dbName),
http.StatusNotFound)
return
}
// Retrieve the metadata for the database
meta, err := com.MetadataResponse(dbOwner, dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Return the list as JSON
jsonList, err := json.MarshalIndent(meta, "", " ")
if err != nil {
errMsg := fmt.Sprintf("Error when JSON marshalling the branch list: %v", err)
log.Print(errMsg)
http.Error(w, errMsg, http.StatusBadRequest)
return
}
fmt.Fprintf(w, string(jsonList))
return
}
// postHandler receives uploaded files from DB4S. To simulate a DB4S upload, the following curl command can be used:
//
// $ curl -kE ~/my.cert.pem -D headers.out -F [email protected] -F "branch=main" -F "commitmsg=stuff" \
// -F "sourceurl=https://example.org" -F "lastmodified=2017-01-02T03:04:05Z" -F "licence=CC0" -F "public=true" \
// https://db4s.dbhub.io:5550/someuser
//
// Subsequent uploads to the same database name will need to include an additional "commit" field, with the value of
// the commit ID last known to DB4S. An example curl command demonstrating this:
//
// $ curl -kE ~/my.cert.pem -D headers.out -F [email protected] -F "branch=main" -F "commitmsg=stuff" \
// -F "sourceurl=https://example.org" -F "lastmodified=2017-01-02T03:04:05Z" -F "licence=CC0" -F "public=true" \
// -F "commit=51d494f2c5eb6734ddaa204eccb9597b426091c79c951924ac83c72038f22b55" \
// https://db4s.dbhub.io:5550/someuser
func postHandler(w http.ResponseWriter, r *http.Request, userAcc string) {
// Set the maximum accepted database size for uploading
maxSize, err := database.MaxUploadSizeForUser(userAcc)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if maxSize != -1 {
r.Body = http.MaxBytesReader(w, r.Body, maxSize)
}
// The "public" user isn't allowed to make changes
if userAcc == "public" {
log.Printf("User from '%s' attempted to add a database using the public certificate", r.RemoteAddr)
http.Error(w, "You're using the 'public' certificate, which isn't allowed to make changes on the server",
http.StatusUnauthorized)
return
}
// Split the request URL into path components
pathStrings := strings.Split(r.URL.Path, "/")
// Ensure a target username was given
targetUser := pathStrings[1]
if targetUser == "" {
http.Error(w, "Missing target user", http.StatusBadRequest)
return
}
// Validate the target user
err = com.ValidateUser(targetUser)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Check whether the uploaded database is too large
if maxSize != -1 {
if r.ContentLength > maxSize {
http.Error(w,
fmt.Sprintf("Database is too large. Maximum database upload size is %d MB, yours is %d MB",
maxSize/1024/1024, r.ContentLength/1024/1024), http.StatusBadRequest)
log.Println(fmt.Sprintf("'%s' attempted to upload an oversized database %d MB in size. Limit is %d MB",
userAcc, r.ContentLength/1024/1024, maxSize/1024/1024))
return
}
}
// Do the remaining input validation, and add the database to the system in the appropriate spot
m, httpStatus, err := com.UploadResponse(w, r, userAcc, targetUser, "", "", "db4s")
if err != nil {
http.Error(w, err.Error(), httpStatus)
return
}
// Convert to JSON
var msg bytes.Buffer
enc := json.NewEncoder(&msg)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(m); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send return message back to the client
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, msg.String())
}
// Returns a file requested by the client. An example curl command to simulate the request is:
//
// $ curl -OL -kE ~/my.cert.pem -D headers.out -G https://db4s.dbhub.io:5550/someuser/somedb.sqlite
func retrieveDatabase(w http.ResponseWriter, r *http.Request, pageName string, userAcc string, dbOwner string,
dbName string, branchName string, commit string) (err error) {
pageName += ":retrieveDatabase()"
// Retrieve the Minio details and last modified date for the requested database
bucket, id, lastMod, err := com.MinioLocation(dbOwner, dbName, commit, userAcc)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Get a handle from Minio for the database object
userDB, err := com.MinioHandle(bucket, id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Close the object handle when this function finishes
defer func() {
err := com.MinioHandleClose(userDB)
if err != nil {
log.Printf("%s: Error closing object handle: %v", pageName, err)
}
}()
// Get the file details
stat, err := userDB.Stat()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Was a user agent part of the request?
var userAgent string
ua, ok := r.Header["User-Agent"]
if ok {
userAgent = ua[0]
}
// Make a record of the download
err = database.LogDownload(dbOwner, dbName, userAcc, r.RemoteAddr, "db4s", userAgent, time.Now().UTC(),
bucket+id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Send the database to the user
// Note: modification-date parameter format copied from RFC 2183 (the closest match I could find easily)
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"; modification-date="%s";`,
url.QueryEscape(dbName), lastMod.Format(time.RFC3339)))
w.Header().Set("Content-Length", fmt.Sprintf("%d", stat.Size))
w.Header().Set("Content-Type", "application/x-sqlite3")
w.Header().Set("Branch", branchName)
w.Header().Set("Commit-ID", commit)
bytesWritten, err := io.Copy(w, userDB)
if err != nil {
log.Printf("%s: Error returning DB file: %v", pageName, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// If downloaded by someone other than the owner, increment the download count for the database
if strings.ToLower(userAcc) != strings.ToLower(dbOwner) {
err = database.IncrementDownloadCount(dbOwner, dbName)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Log the transfer
log.Printf("'%s/%s' downloaded by user '%v', %v bytes", com.SanitiseLogString(dbOwner),
com.SanitiseLogString(dbName), userAcc, bytesWritten)
return nil
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
pageName := "Main page"
// Extract the account name and associated server from the validated client certificate
userAcc, _, err := extractUserAndServer(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// The handler to use depends upon the request type
reqType := r.Method
switch reqType {
case "GET":
getHandler(w, r, userAcc)
case "POST":
postHandler(w, r, userAcc)
default:
log.Printf("%s: Unknown request method received from '%v", pageName, userAcc)
http.Error(w, fmt.Sprintf("Unknown request type: %v", reqType), http.StatusBadRequest)
}
return
}
// Returns the list of databases available to the user. To simulate, the following curl command can be used:
//
// $ curl -kE ~/my.cert.pem -D headers.out -G https://db4s.dbhub.io:5550/someuser
func userDatabaseList(userAcc string, user string) (dbList []byte, err error) {
// Structure to hold the results, to apply JSON marshalling to
type linkRow struct {
CommitID string `json:"commit_id"`
DefBranch string `json:"default_branch"`
LastModified string `json:"last_modified"`
Licence string `json:"licence"`
Name string `json:"name"`
OneLineDesc string `json:"one_line_description"`
Public bool `json:"public"`
RepoModified string `json:"repo_modified"`
SHA256 string `json:"sha256"`
Size int64 `json:"size"`
Type string `json:"type"`
URL string `json:"url"`
}
// Retrieve the list of databases for the requested username. Only include those accessible to the logged
// in user (userAcc) though
var pubSetting database.AccessType
if strings.ToLower(userAcc) != strings.ToLower(user) {
// The user is requesting someone else's list, so only return public databases
pubSetting = database.DB_PUBLIC
} else {
// The logged in user is requesting their own database list, so give them both public and private
pubSetting = database.DB_BOTH
}
// Retrieve the database list
pubDBs, err := database.UserDBs(user, pubSetting)
if err != nil {
return nil, err