-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenconfig.go
More file actions
706 lines (619 loc) · 19.4 KB
/
Copy pathgenconfig.go
File metadata and controls
706 lines (619 loc) · 19.4 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
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
package main
import (
"bytes"
"context"
"crypto/x509"
_ "embed"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"text/template"
"time"
"github.com/getlantern/fronted"
"github.com/getlantern/golog"
"github.com/getlantern/keyman"
"github.com/getlantern/tlsdialer/v3"
"github.com/getlantern/yaml"
"github.com/getlantern/flashlight/v7/common"
"github.com/getlantern/flashlight/v7/config"
"github.com/getlantern/flashlight/v7/embeddedconfig"
tls "github.com/refraction-networking/utls"
)
const (
ftVersionFile = `https://raw.githubusercontent.com/firetweet/downloads/master/version.txt`
defaultDeviceID = "555"
defaultProviderID = "cloudfront"
)
var (
help = flag.Bool("help", false, "Get usage help")
minMasquerades = flag.Int("min-masquerades", 1000, "Require that the resulting config contain at least this many masquerades per provider")
maxMasquerades = flag.Int("max-masquerades", 1000, "Limit the number of masquerades to include in config per provider")
blacklistFile = flag.String("blacklist", "", "Path to file containing list of blacklisted domains, which will be excluded from the configuration even if present in the masquerades file (e.g. blacklist.txt)")
proxiedSitesDir = flag.String("proxiedsites", "proxiedsites", "Path to directory containing proxied site lists, which will be combined and proxied by Lantern")
minFreq = flag.Float64("minfreq", 3.0, "Minimum frequency (percentage) for including CA cert in list of trusted certs, defaults to 3.0%")
numberOfWorkers = flag.Int("numworkers", 50, "Number of worker threads")
dnsttFile = flag.String("dnstt-file", "", "Path to yaml file containing DNSTT config")
enabledProviders stringsFlag // --enable-provider in init()
masqueradesInFiles stringsFlag // --masquerades in init()
)
var (
log = golog.LoggerFor("genconfig")
masquerades []string
blacklist = make(filter)
proxiedSites = make(filter)
)
type ConfigGenerator struct {
ftVersion string
inputCh chan string
masqueradesCh chan *masquerade
wg sync.WaitGroup
Providers map[string]*provider // supported fronting providers
verifier verifier
certGrabber certGrabber
}
//go:generate mockgen -destination ./mock_genconfig.go -source ./genconfig.go -package main verifier, certGrabber
type verifier interface {
Vet(m *fronted.Masquerade, pool *x509.CertPool, testURL string) bool
}
type certGrabber interface {
GetCertificate(ip, domain string) (*keyman.Certificate, error)
}
type frontedVerifier struct{}
func (frontedVerifier) Vet(m *fronted.Masquerade, pool *x509.CertPool, testURL string) bool {
return fronted.Vet(m, pool, testURL)
}
type grabCert struct{}
func (g *grabCert) GetCertificate(ip, domain string) (*keyman.Certificate, error) {
if !strings.Contains(ip, ":") {
ip = net.JoinHostPort(ip, "443")
}
cwt, err := tlsdialer.DialForTimings(net.DialTimeout, 10*time.Second, "tcp", ip, false, &tls.Config{ServerName: domain})
if err != nil {
log.Errorf("Unable to dial IP %s, domain %s: %s", ip, domain, err)
return nil, err
}
if err := cwt.Conn.Close(); err != nil {
log.Debugf("Error closing connection: %v", err)
return nil, err
}
chain := cwt.VerifiedChains[0]
rootCA := chain[len(chain)-1]
rootCert, err := keyman.LoadCertificateFromX509(rootCA)
if err != nil {
log.Errorf("Unable to load keyman certificate: %s", err)
return nil, err
}
return rootCert, nil
}
func NewConfigGenerator() *ConfigGenerator {
return &ConfigGenerator{
inputCh: make(chan string),
masqueradesCh: make(chan *masquerade),
Providers: loadMapping(),
wg: sync.WaitGroup{},
verifier: frontedVerifier{},
certGrabber: &grabCert{},
}
}
//go:embed provider_map.yaml
var mappingData []byte
func loadMapping() map[string]*provider {
var mapping map[string]ProviderConfig
err := yaml.Unmarshal(mappingData, &mapping)
if err != nil {
panic(fmt.Errorf("mapping file is invalid: %w", err))
}
providers := make(map[string]*provider)
for name, p := range mapping {
providers[name] = newProvider(p.Ping, p.Mapping, p.FrontingSNIs, &config.ValidatorConfig{RejectStatus: []int{p.RejectStatus}}, p.VerifyHostname)
}
return providers
}
type ProviderConfig struct {
Ping string `yaml:"ping"`
RejectStatus int `yaml:"rejectStatus"`
Mapping map[string]string `yaml:"mapping"`
FrontingSNIs map[string]*fronted.SNIConfig `yaml:"frontingsnis"`
VerifyHostname *string `yaml:"verifyHostname,omitempty"`
}
type filter map[string]bool
type masquerade struct {
Domain string
IpAddress string
ProviderID string
RootCA *castat
}
type castat struct {
CommonName string
Cert string
total int64
byProvider map[string]int64
}
type provider struct {
HostAliases map[string]string
TestURL string
Masquerades []*masquerade
Validator *config.ValidatorConfig
Enabled bool
FrontingSNIs map[string]*fronted.SNIConfig
VerifyHostname *string
}
func newProvider(testURL string, hosts map[string]string, frontingSNIs map[string]*fronted.SNIConfig, validator *config.ValidatorConfig, verifyHostname *string) *provider {
return &provider{
HostAliases: hosts,
TestURL: testURL,
Masquerades: make([]*masquerade, 0),
Validator: validator,
FrontingSNIs: frontingSNIs,
VerifyHostname: verifyHostname,
}
}
type stringsFlag []string
func (ss *stringsFlag) String() string {
return strings.Join(*ss, ",")
}
func (ss *stringsFlag) Set(value string) error {
*ss = append(*ss, value)
return nil
}
func (c *ConfigGenerator) GenerateConfig(
ctx context.Context,
yamlTmpl string,
masquerades []string,
proxiedSites, blacklist filter,
numberOfWorkers int,
minFreq float64,
minMasquerades, maxMasquerades int,
dnsttConfig *common.DNSTTConfig,
) ([]byte, error) {
if err := c.loadFtVersion(); err != nil {
return nil, err
}
go c.feedMasquerades()
cas, masqs := c.coalesceMasquerades()
if err := c.vetAndAssignMasquerades(cas, masqs, minMasquerades, maxMasquerades, numberOfWorkers); err != nil {
return nil, err
}
model, err := c.buildModel("cloud.yaml", cas, dnsttConfig)
if err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
return generateTemplate(model, yamlTmpl)
}
func main() {
flag.Var(&masqueradesInFiles, "masquerades", "Path to file containing list of masquerades to use, with one space-separated 'ip domain provider' set per line (e.g. masquerades.txt)")
flag.Var(&enabledProviders, "enable-provider", "Enable fronting provider")
flag.Parse()
if *help {
flag.Usage()
os.Exit(1)
}
generator := NewConfigGenerator()
numcores := runtime.NumCPU()
log.Debugf("Using all %d cores on machine", numcores)
runtime.GOMAXPROCS(numcores)
for _, pid := range enabledProviders {
p, ok := generator.Providers[pid]
if !ok {
log.Fatalf("Invalid/Unknown fronting provider: %s", pid)
}
p.Enabled = true
}
loadMasquerades()
loadProxiedSitesList()
loadBlacklist()
dnsttCfg, err := loadDNSTTConfig()
if err != nil {
log.Errorf("Error loading DNSTT config: %s", err)
}
yamlTmpl := string(embeddedconfig.GlobalTemplate)
template, err := generator.GenerateConfig(
context.Background(),
yamlTmpl,
masquerades,
proxiedSites,
blacklist,
*numberOfWorkers,
*minFreq,
*minMasquerades,
*maxMasquerades,
dnsttCfg,
)
if err != nil {
log.Fatalf("Error generating configuration: %s", err)
}
if err := os.WriteFile("cloud.yaml", template, 0644); err != nil {
log.Fatalf("Error writing configuration: %s", err)
}
}
func loadMasquerades() {
if len(masqueradesInFiles) == 0 {
log.Error("Please specify a masquerades file")
flag.Usage()
os.Exit(2)
}
for _, filename := range masqueradesInFiles {
bytes, err := os.ReadFile(filename)
if err != nil {
log.Fatalf("Unable to read masquerades file at %s: %s", filename, err)
}
masquerades = append(masquerades, strings.Split(string(bytes), "\n")...)
}
}
// Scans the proxied site directory and stores the sites in the files found
func loadProxiedSites(path string, info os.FileInfo, err error) error {
if err != nil {
log.Fatalf("Error accessing path %q: %v\n", path, err)
return err
}
if info.IsDir() {
// skip root directory
return nil
}
proxiedSiteBytes, err := os.ReadFile(path)
if err != nil {
log.Fatalf("Unable to read blacklist file at %s: %s", path, err)
}
for _, domain := range strings.Split(string(proxiedSiteBytes), "\n") {
// skip empty lines, comments, and *.ir sites
// since we're focusing on Iran with this first release, we aren't adding *.ir sites
// to the global proxied sites
// to avoid proxying sites that are already unblocked there.
// This is a general problem when you aren't maintaining country-specific whitelists
// which will be addressed in the next phase
if domain != "" && !strings.HasPrefix(domain, "#") && !strings.HasSuffix(domain, ".ir") {
proxiedSites[domain] = true
}
}
return err
}
func loadProxiedSitesList() {
if *proxiedSitesDir == "" {
log.Error("Please specify a proxied site directory")
flag.Usage()
os.Exit(3)
}
err := filepath.Walk(*proxiedSitesDir, loadProxiedSites)
if err != nil {
log.Errorf("Could not open proxied site directory: %s", err)
}
}
func (c *ConfigGenerator) loadFtVersion() error {
res, err := http.Get(ftVersionFile)
if err != nil {
return fmt.Errorf("error fetching FireTweet version file: %w", err)
}
defer func() {
_ = res.Body.Close()
}()
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("could not read FT version file: %w", err)
}
c.ftVersion = strings.TrimSpace(string(body))
return nil
}
func loadBlacklist() {
if *blacklistFile == "" {
log.Error("Please specify a blacklist file")
flag.Usage()
os.Exit(3)
}
blacklistBytes, err := os.ReadFile(*blacklistFile)
if err != nil {
log.Fatalf("Unable to read blacklist file at %s: %s", *blacklistFile, err)
}
for _, domain := range strings.Split(string(blacklistBytes), "\n") {
blacklist[domain] = true
}
}
func loadDNSTTConfig() (*common.DNSTTConfig, error) {
if *dnsttFile == "" {
return nil, nil
}
bytes, err := os.ReadFile(*dnsttFile)
if err != nil {
return nil, fmt.Errorf("Unable to read dnstt file at %s: %s", *dnsttFile, err)
}
var cfg common.DNSTTConfig
if err := yaml.Unmarshal(bytes, &cfg); err != nil {
return nil, fmt.Errorf("Unable to parse dnstt file at %s: %s", *dnsttFile, err)
}
if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("Invalid DNSTT config: %s", err)
}
return &cfg, nil
}
func loadTemplate(name string) string {
bytes, err := os.ReadFile(name)
if err != nil {
log.Fatalf("Unable to load template %s: %s", name, err)
}
return string(bytes)
}
func (c *ConfigGenerator) feedMasquerades() {
c.wg.Add(*numberOfWorkers)
for i := 0; i < *numberOfWorkers; i++ {
go c.grabCerts()
}
// feed masquerades in random order to get different order each time we run
randomOrder := rand.Perm(len(masquerades))
for _, i := range randomOrder {
masq := masquerades[i]
if masq != "" {
c.inputCh <- masq
}
}
close(c.inputCh)
c.wg.Wait()
close(c.masqueradesCh)
}
// grabCerts grabs certificates for the masquerades received on masqueradesCh and sends
// *masquerades to masqueradesCh.
func (c *ConfigGenerator) grabCerts() {
defer c.wg.Done()
for masq := range c.inputCh {
parts := strings.Split(masq, " ")
var providerID string
if len(parts) == 2 {
providerID = defaultProviderID
} else if len(parts) == 3 {
providerID = parts[2]
} else {
log.Error("Bad line! '" + masq + "'")
continue
}
provider, ok := c.Providers[providerID]
if !ok {
log.Debugf("Skipping masquerade for unknown provider %s", providerID)
continue
}
// default provider is always vetted even if not enabled for legacy client config
if providerID != defaultProviderID && !provider.Enabled {
log.Debugf("Skipping masquerade for disabled provider %s", providerID)
}
ip := parts[0]
domain := parts[1]
_, blacklisted := blacklist[domain]
if blacklisted {
log.Tracef("Domain %s is blacklisted, skipping", domain)
continue
}
log.Tracef("Grabbing certs for IP %s, domain %s", ip, domain)
rootCert, err := c.certGrabber.GetCertificate(ip, domain)
if err != nil {
continue
}
ca := &castat{
CommonName: rootCert.X509().Subject.CommonName,
Cert: strings.Replace(string(rootCert.PEMEncoded()), "\n", "\\n", -1),
byProvider: make(map[string]int64),
}
log.Debugf("Successfully grabbed certs for: %v", domain)
c.masqueradesCh <- &masquerade{
Domain: domain,
IpAddress: ip,
ProviderID: providerID,
RootCA: ca,
}
}
}
func (c *ConfigGenerator) coalesceMasquerades() (map[string]*castat, []*masquerade) {
count := make(map[string]int) // by provider
allCAs := make(map[string]*castat)
allMasquerades := make([]*masquerade, 0)
for m := range c.masqueradesCh {
ca := allCAs[m.RootCA.Cert]
if ca == nil {
ca = m.RootCA
}
count[m.ProviderID] += 1
ca.byProvider[m.ProviderID] += 1
ca.total += 1
allCAs[ca.Cert] = ca
allMasquerades = append(allMasquerades, m)
}
// Trust only those cas whose relative frequency exceeds *minFreq
// for some provider.
trustedCAs := make(map[string]*castat)
for _, ca := range allCAs {
for pid, cc := range ca.byProvider {
freq := float64(cc*100) / float64(count[pid])
log.Debugf("CA %s has freq %f for provider %s", ca.CommonName, freq, pid)
if freq > *minFreq {
trustedCAs[ca.Cert] = ca
log.Debugf("Trusting CA %s", ca.CommonName)
break
}
}
}
// Pick only the masquerades associated with the trusted certs
trustedMasquerades := make([]*masquerade, 0)
for _, m := range allMasquerades {
_, caFound := trustedCAs[m.RootCA.Cert]
if caFound {
trustedMasquerades = append(trustedMasquerades, m)
}
}
return trustedCAs, trustedMasquerades
}
func (c *ConfigGenerator) vetAndAssignMasquerades(cas map[string]*castat, masquerades []*masquerade, minMasquerades, maxMasquerades, numOfWorkers int) error {
byProvider := make(map[string][]*masquerade, 0)
for _, m := range masquerades {
byProvider[m.ProviderID] = append(byProvider[m.ProviderID], m)
}
for pid, candidates := range byProvider {
provider, ok := c.Providers[pid]
if !ok {
log.Debugf("Not vetting masquerades for unknown provider %s", pid)
continue
}
if !provider.Enabled {
log.Debugf("Not vetting masquerades for disabled provider %s", pid)
}
vetted := c.vetMasquerades(cas, candidates, numOfWorkers, maxMasquerades)
if len(vetted) < minMasquerades {
log.Fatalf("%s: %d masquerades was fewer than minimum of %d", pid, len(vetted), minMasquerades)
return fmt.Errorf("%s: %d masquerades was fewer than minimum of %d", pid, len(vetted), minMasquerades)
}
provider.Masquerades = vetted
}
return nil
}
func (c *ConfigGenerator) vetMasquerades(cas map[string]*castat, masquerades []*masquerade, numberOfWorkers int, maxMasquerades int) []*masquerade {
certPool := x509.NewCertPool()
for _, ca := range cas {
cert, err := keyman.LoadCertificateFromPEMBytes([]byte(strings.Replace(ca.Cert, `\n`, "\n", -1)))
if err != nil {
log.Errorf("Unable to parse certificate: %v", err)
continue
}
certPool.AddCert(cert.X509())
log.Debug("Added cert to pool")
}
c.wg.Add(numberOfWorkers)
inCh := make(chan *masquerade, len(masquerades))
outCh := make(chan *masquerade, len(masquerades))
for _, masquerade := range masquerades {
inCh <- masquerade
}
close(inCh)
for i := 0; i < numberOfWorkers; i++ {
go c.doVetMasquerades(certPool, inCh, outCh)
}
c.wg.Wait()
close(outCh)
result := make([]*masquerade, 0, maxMasquerades)
count := 0
for masquerade := range outCh {
result = append(result, masquerade)
count++
if count == maxMasquerades {
break
}
}
return result
}
func (c *ConfigGenerator) doVetMasquerades(certPool *x509.CertPool, inCh chan *masquerade, outCh chan *masquerade) {
log.Debug("Starting to vet masquerades")
for masquerade := range inCh {
m := &fronted.Masquerade{
Domain: masquerade.Domain,
IpAddress: masquerade.IpAddress,
}
provider, ok := c.Providers[masquerade.ProviderID]
if !ok {
log.Debugf("%v (%v) failed to vet: unknown provider %v", m.Domain, m.IpAddress, masquerade.ProviderID)
continue
}
if c.verifier.Vet(m, certPool, provider.TestURL) {
log.Debugf("Successfully vetted %v (%v)", m.Domain, m.IpAddress)
outCh <- masquerade
} else {
log.Debugf("%v (%v) failed to vet", m.Domain, m.IpAddress)
}
}
log.Debug("Done vetting masquerades")
c.wg.Done()
}
func (c *ConfigGenerator) buildModel(configName string, cas map[string]*castat, dnsttCfg *common.DNSTTConfig) (map[string]interface{}, error) {
casList := make([]*castat, 0, len(cas))
for _, ca := range cas {
casList = append(casList, ca)
}
sort.Sort(ByTotal(casList))
cfMasquerades := c.Providers[defaultProviderID].Masquerades
if len(cfMasquerades) == 0 {
return nil, fmt.Errorf("%s: configuration contains no cloudfront masquerades for older clients.", configName)
}
aliased := make(map[string]bool)
enabledProviders := make(map[string]*provider)
for k, v := range c.Providers {
if v.Enabled {
if len(v.Masquerades) > 0 {
sort.Sort(ByDomain(v.Masquerades))
enabledProviders[k] = v
} else {
return nil, fmt.Errorf("%s: enabled provider %s had no vetted masquerades", configName, k)
}
}
for a, _ := range v.HostAliases {
aliased[a] = true
}
}
for pid, p := range enabledProviders {
for a, _ := range aliased {
_, ok := p.HostAliases[a]
if !ok {
return nil, fmt.Errorf("%s: configured provider %s does not have an alias for origin %s", configName, pid, a)
}
}
}
ps := make([]string, 0, len(proxiedSites))
for site, _ := range proxiedSites {
ps = append(ps, site)
}
sort.Strings(ps)
return map[string]interface{}{
"cas": casList,
"cloudfrontMasquerades": cfMasquerades,
"providers": enabledProviders,
"proxiedsites": ps,
"ftVersion": c.ftVersion,
"dnstt": dnsttCfg,
}, nil
}
func generateTemplate(model map[string]interface{}, tmplString string) ([]byte, error) {
tmpl, err := template.New("").Funcs(funcMap).Parse(tmplString)
if err != nil {
log.Errorf("Unable to parse template: %s", err)
return []byte{}, err
}
var out bytes.Buffer
err = tmpl.Execute(&out, model)
if err != nil {
log.Errorf("Unable to generate: %s", err)
}
return out.Bytes(), nil
}
func run(prg string, args ...string) (string, error) {
cmd := exec.Command(prg, args...)
log.Debugf("Running %s %s", prg, strings.Join(args, " "))
out, err := cmd.CombinedOutput()
if err != nil {
return "", fmt.Errorf("%s says %s", prg, string(out))
}
return string(out), nil
}
func base64Encode(sites []string) string {
raw, err := json.Marshal(sites)
if err != nil {
panic(fmt.Errorf("Unable to marshal proxied sites: %s", err))
}
b64 := base64.StdEncoding.EncodeToString(raw)
return b64
}
// the functions to be called from template
var funcMap = template.FuncMap{
"encode": base64Encode,
}
type ByDomain []*masquerade
func (a ByDomain) Len() int { return len(a) }
func (a ByDomain) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByDomain) Less(i, j int) bool { return a[i].Domain < a[j].Domain }
type ByTotal []*castat
func (a ByTotal) Len() int { return len(a) }
func (a ByTotal) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByTotal) Less(i, j int) bool { return a[i].total > a[j].total }