-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
2186 lines (1985 loc) · 52.5 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
import (
"bytes"
"container/list"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
"os"
"os/exec"
"os/signal"
"path/filepath"
"plugin"
"regexp"
"runtime"
"sort"
"strings"
"sync"
"syscall"
"time"
"github.com/elitah/fast-io"
"github.com/elitah/utils/autocert"
"github.com/elitah/utils/exepath"
"github.com/elitah/utils/hash"
"github.com/elitah/utils/logs"
"github.com/elitah/utils/random"
"github.com/inconshreveable/go-vhost"
"github.com/panjf2000/ants"
)
var (
rootDir = exepath.GetExeDir()
)
type HTTPStat struct {
s_http uint64
s_https uint64
f_http uint64
f_https uint64
}
func (this *HTTPStat) AddAttach(https bool) {
if https {
this.s_https++
} else {
this.s_http++
}
}
func (this *HTTPStat) AddFault(https bool) {
if https {
this.f_https++
} else {
this.f_http++
}
}
func (this *HTTPStat) String() string {
return fmt.Sprintf(`<td class="green">%d</td><td class="green">%d</td><td class="red">%d</td><td class="red">%d</td>`,
this.s_http, this.s_https, this.f_http, this.f_https)
}
type SuffixRule interface {
ChkSuffix(string) bool
}
type HTTPRule struct {
PluginHandler func(w http.ResponseWriter, r *http.Request)
AutoCert bool
HTTPSUp bool
Target string
Suffix string
}
func (this *HTTPRule) ChkSuffix(key string) bool {
if "" != this.Suffix {
return strings.HasSuffix(key, this.Suffix)
}
return false
}
type HTTPSRule struct {
PluginHandler func(w http.ResponseWriter, r *http.Request)
AutoCert bool
Redirect bool
Target string
Suffix string
AuthBase64 string
AnonymousDir []string
}
func (this *HTTPSRule) ChkSuffix(key string) bool {
if "" != this.Suffix {
return strings.HasSuffix(key, this.Suffix)
}
return false
}
type AuthNode struct {
start int64
end int64
}
func (this *AuthNode) Available() bool {
return 0 == this.start || (0 < this.end && this.end <= time.Now().Unix()) || (this.start+600) <= time.Now().Unix()
}
func (this *AuthNode) Success() bool {
return 0 < this.end && this.end > time.Now().Unix()
}
type HostList struct {
sync.RWMutex
ListenHttpPort int
ListenHttpsPort int
AcceptIP bool
MasterDomain string
mAntsPool *ants.Pool
mList *list.List
mListHTTP map[string]*HTTPRule
mListHTTPS map[string]*HTTPSRule
mListSuffix []SuffixRule
mStat map[string]*HTTPStat
mCC chan net.Conn
mPool *sync.Pool
mCookieSID string
mCookieValidity int
mRegexpCookie *regexp.Regexp
mRegexpDomain *regexp.Regexp
mRegexpIPAddr *regexp.Regexp
mRegexpIPPort *regexp.Regexp
mHttpAuth string
mClient *http.Client
mAutoCert *autocert.AutoCertManager
mSSLAddr net.Addr
mReCAPTCHA string
mReCAPTCHAVerify string
mGlobalCertFilepath string
mGlobalKeyFilepath string
mGlobalCAFilepath string
mAuthCode map[string]*AuthNode
}
func NewHostList(pool *ants.Pool) *HostList {
jar, err := cookiejar.New(nil)
if nil != err {
logs.Warn(err)
} else {
if nil != jar {
}
}
return &HostList{
ListenHttpPort: 80,
ListenHttpsPort: 443,
AcceptIP: false,
MasterDomain: "",
mAntsPool: pool,
mList: list.New(),
mListHTTP: make(map[string]*HTTPRule),
mListHTTPS: make(map[string]*HTTPSRule),
mStat: make(map[string]*HTTPStat),
mCC: make(chan net.Conn),
mPool: &sync.Pool{
New: func() interface{} {
return make([]byte, 32*1024)
},
},
mCookieSID: random.NewRandomString(random.ModeNoLine, 16),
mCookieValidity: 1800,
mRegexpCookie: regexp.MustCompile(`^__auth_token_\d{10}__$`),
mRegexpDomain: regexp.MustCompile(`(\w+\.)+\w+`),
mRegexpIPAddr: regexp.MustCompile(`(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)`),
mRegexpIPPort: regexp.MustCompile(`^(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d):([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{4}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$`),
mClient: &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
//Jar: jar,
},
mAuthCode: make(map[string]*AuthNode),
}
}
func (this *HostList) LoadConfig(path string) bool {
if "" == path {
if file, err := exec.LookPath(os.Args[0]); nil == err {
if _path, err := filepath.Abs(file); nil == err {
if _path := filepath.Dir(_path); "" != _path {
path = _path + "/config.json"
}
}
}
}
if "" != path {
if content, err := ioutil.ReadFile(path); nil == err {
type rule struct {
HttpTo string `json:"http_to"`
HttpsTo string `json:"https_to"`
AnonymousDir []string `json:"anonymous_dir"`
}
list := &struct {
HTTP int `json:"http"`
HTTPS int `json:"https"`
AcceptIP bool `json:"accept_ip"`
CookieValidity int `json:"cookie_validity"`
ReCAPTCHA string `json:"recaptcha"`
ReCAPTCHAVerify string `json:"recaptcha_verify"`
GlobalCertFilepath string `json:"global_cert_filepath"`
GlobalKeyFilepath string `json:"global_key_filepath"`
GlobalCAFilepath string `json:"global_ca_filepath"`
Domain string `json:"domain"`
Username string `json:"username"`
Password string `json:"password"`
Suffix map[string]*rule `json:"suffix"`
List map[string]*rule `json:"list"`
}{}
if err := json.Unmarshal(content, list); nil == err {
// 用于统计域名,方便排序
var domains []string
// 读取参数
if 0 < list.HTTP && 65536 > list.HTTP {
this.ListenHttpPort = list.HTTP
}
if 0 < list.HTTPS && 65536 > list.HTTPS {
this.ListenHttpsPort = list.HTTPS
}
// 接受IP访问
this.AcceptIP = list.AcceptIP
// Cookie超时
if this.mCookieValidity < list.CookieValidity {
this.mCookieValidity = list.CookieValidity
}
// reCaptcha v3 api key
if "" != list.ReCAPTCHA && "" != list.ReCAPTCHAVerify {
this.mReCAPTCHA = list.ReCAPTCHA
this.mReCAPTCHAVerify = list.ReCAPTCHAVerify
}
// cert chain
if "" != list.GlobalCertFilepath && "" != list.GlobalKeyFilepath {
this.mGlobalCertFilepath = list.GlobalCertFilepath
this.mGlobalKeyFilepath = list.GlobalKeyFilepath
this.mGlobalCAFilepath = list.GlobalCAFilepath
}
if "" != list.Domain {
if nil != this.mRegexpDomain && this.mRegexpDomain.MatchString(list.Domain) {
// 赋值主域名
this.MasterDomain = list.Domain
// 存入列表
this.mListHTTP[list.Domain] = &HTTPRule{
AutoCert: true,
Target: list.Domain,
}
// 存入列表
this.mListHTTPS[list.Domain] = &HTTPSRule{
AutoCert: true,
Target: list.Domain,
}
}
}
if "" != list.Username && "" != list.Password {
this.mHttpAuth = base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", list.Username, list.Password)))
}
// 先统计域名
for key, _ := range list.Suffix {
if "" != key && '.' == key[0] && 4 <= len(key) {
domains = append(domains, key)
}
}
for key, _ := range list.List {
if "" != key && "*" != key && 3 <= len(key) {
domains = append(domains, key)
}
}
// 排序
sort.Strings(domains)
// 添加全局
domains = append(domains, "*")
// 遍历列表并添加规则
for _, domain := range domains {
var r *rule
if '.' == domain[0] {
if _r, ok := list.Suffix[domain]; ok {
r = _r
}
}
if nil == r {
if _r, ok := list.List[domain]; ok {
r = _r
}
}
if nil != r {
if "" != r.HttpTo {
if this.AddHTTP(domain, r.HttpTo, r.AnonymousDir) {
logs.Info("AddHTTP: %s => %s Success", domain, r.HttpTo)
} else {
logs.Warn("AddHTTP: %s XX %s Failed", domain, r.HttpTo)
}
}
if "" != r.HttpsTo {
if this.AddHTTPS(domain, r.HttpsTo) {
logs.Info("AddHTTPS: %s => %s Success", domain, r.HttpsTo)
} else {
logs.Warn("AddHTTPS: %s XX %s Failed", domain, r.HttpsTo)
}
}
}
}
return true
} else {
logs.Warn("Config: parse json failed,", err)
}
}
}
return false
}
func (this *HostList) LoadPlugin(fullpath string) string {
var tmppath string
// 创建临时文件
if tmpfile, err := ioutil.TempFile("", fmt.Sprintf("plugin.so.%v.", time.Now().Unix())); nil == err {
// 退出时删除
defer os.Remove(tmpfile.Name())
// 复制文件
if content, err := ioutil.ReadFile(fullpath); nil == err {
if n, err := tmpfile.Write(content); nil == err {
if 0 < n {
tmppath = tmpfile.Name()
} else {
logs.Warn("File empty copy")
}
} else {
logs.Warn(err)
}
} else {
logs.Warn(err)
}
} else {
logs.Warn(err)
}
if "" != tmppath {
if p, err := plugin.Open(tmppath); nil == err {
if h1, err := p.Lookup("VHostRegister"); nil == err {
if h2, err := p.Lookup("VHostHandler"); nil == err {
if VHostRegister, ok := h1.(func() (string, bool, bool, bool)); ok {
if VHostHandler, ok := h2.(func(w http.ResponseWriter, r *http.Request)); ok {
if domain, https, autocert, http_up := VHostRegister(); "" != domain {
if this.AddPlugin(domain, https, autocert, http_up, VHostHandler) {
return domain
} else {
logs.Warn("Call AddPlugin return failed")
}
} else {
logs.Warn("Unable call VHostRegister")
}
} else {
logs.Warn("Unable get VHostHandler")
}
} else {
logs.Warn("Unable get VHostRegister")
}
} else {
logs.Warn(err)
}
} else {
logs.Warn(err)
}
} else {
logs.Warn(err)
}
}
return ""
}
func (this *HostList) AddHTTP(domain, target string, anonymous_dir []string) bool {
if "" != domain && "" != target {
// 标记
var autocert, https_up bool
// 用户名和密码
var username, password string
// 正则测试
if '.' != domain[0] && "*" != domain && nil != this.mRegexpDomain {
if !this.mRegexpDomain.MatchString(domain) {
return false
}
}
// 检查是否是自动证书模式
if 11 < len(target) && strings.HasPrefix(target, "autocert://") {
if u, err := url.Parse(target); nil == err {
// 获取用户名和密码
if nil != u.User {
username = u.User.Username()
if _password, ok := u.User.Password(); ok {
password = _password
} else {
password = username
}
}
// 获取地址
target = u.Host
// 标记
autocert = true
} else {
return false
}
// 检查是否是强制跳转HTTPS模式
} else if 8 < len(target) && strings.HasPrefix(target, "https://") {
// 标记
https_up = true
// 正则测试
if nil != this.mRegexpDomain {
if !this.mRegexpDomain.MatchString(target[8:len(target)]) {
return false
}
}
}
// 如果不是强制跳转HTTPS,检查目标是否为ip:port形式
if !https_up {
// 正则测试
if nil != this.mRegexpIPPort {
if !this.mRegexpIPPort.MatchString(target) {
return false
}
}
}
if _, ok := this.mListHTTP[domain]; !ok {
var rule *HTTPRule
// 根据不同模式创建规则
if autocert {
if _, ok := this.mListHTTPS[domain]; !ok {
if '.' == domain[0] {
this.mListHTTPS[domain] = &HTTPSRule{
AutoCert: autocert,
Target: target,
Suffix: domain,
}
} else {
// 先创建
_rule := &HTTPSRule{
AutoCert: autocert,
Target: target,
}
// 填写用户名和密码
if "" != username && "" != password {
_rule.AuthBase64 = base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", username, password)))
}
if 0 < len(anonymous_dir) {
_rule.AnonymousDir = anonymous_dir
}
// 储存
this.mListHTTPS[domain] = _rule
}
rule = &HTTPRule{
AutoCert: autocert,
}
}
} else {
rule = &HTTPRule{
HTTPSUp: https_up,
}
}
if nil != rule {
rule.Target = target
if '.' == domain[0] {
rule.Suffix = domain
this.mListSuffix = append(this.mListSuffix, rule)
return true
}
this.mListHTTP[domain] = rule
return true
}
}
}
return false
}
func (this *HostList) AddHTTPS(domain, target string) bool {
if "" != domain && "" != target {
if "*" != domain && nil != this.mRegexpDomain {
if !this.mRegexpDomain.MatchString(domain) {
return false
}
}
//
autocert := strings.HasPrefix(target, "http://") || strings.HasPrefix(target, "https://")
//
if !autocert {
if nil != this.mRegexpIPPort {
if !this.mRegexpIPPort.MatchString(target) {
return false
}
}
}
if '.' == domain[0] {
for _, _rule := range this.mListSuffix {
if rule, ok := _rule.(*HTTPSRule); ok {
if rule.Suffix == domain {
rule.Target = target
return true
}
}
}
this.mListSuffix = append(this.mListSuffix, &HTTPSRule{
Target: target,
Suffix: domain,
})
return true
}
if _, ok := this.mListHTTPS[domain]; !ok {
this.mListHTTPS[domain] = &HTTPSRule{
Target: target,
AutoCert: autocert,
Redirect: autocert,
}
return true
}
}
return false
}
func (this *HostList) AddPlugin(domain string, https, autocert, http_up bool, fn func(w http.ResponseWriter, r *http.Request)) bool {
if "" != domain && nil != fn {
if nil != this.mRegexpDomain {
if !this.mRegexpDomain.MatchString(domain) {
return false
}
}
if https {
if autocert {
http_up = true
}
if http_up {
this.mListHTTP[domain] = &HTTPRule{
AutoCert: autocert,
HTTPSUp: http_up,
Target: "https://" + domain,
}
}
this.mListHTTPS[domain] = &HTTPSRule{
PluginHandler: fn,
AutoCert: autocert,
}
} else {
this.mListHTTP[domain] = &HTTPRule{
PluginHandler: fn,
}
}
return true
}
return false
}
func (this *HostList) AddAttach(domain string, https ...bool) {
this.Lock()
if s, ok := this.mStat[domain]; ok {
s.AddAttach(0 < len(https) && https[0])
} else {
s = &HTTPStat{}
if 0 < len(https) && https[0] {
s.s_https = 1
} else {
s.s_http = 1
}
this.mStat[domain] = s
}
this.Unlock()
}
func (this *HostList) AddFault(domain string, https ...bool) {
this.Lock()
if s, ok := this.mStat[domain]; ok {
s.AddFault(0 < len(https) && https[0])
} else {
s = &HTTPStat{}
if 0 < len(https) && https[0] {
s.f_https = 1
} else {
s.f_http = 1
}
this.mStat[domain] = s
}
this.Unlock()
}
func (this *HostList) AddViewStatistics(domain string) {
if "" != domain {
this.Lock()
if 32 < this.mList.Len() {
this.mList.Back().Value = domain
this.mList.MoveToFront(this.mList.Back())
} else {
this.mList.PushFront(domain)
}
this.Unlock()
}
}
func (this *HostList) VerifyReCAPTCHA(token string, r *http.Request) bool {
if "" != this.mReCAPTCHA {
if "" != token {
args := url.Values{}
// 校验密钥
args.Add("secret", this.mReCAPTCHAVerify)
// 结果令牌
args.Add("response", token)
// 获取IP
if address := strings.Split(r.RemoteAddr, ":"); 0 < len(address) {
args.Add("remoteip", address[0])
}
// API查验
if resp, err := http.PostForm("https://recaptcha.net/recaptcha/api/siteverify", args); nil == err {
defer resp.Body.Close()
//
if http.StatusOK == resp.StatusCode {
var buffer [1024]byte
//
if n, err := io.ReadFull(resp.Body, buffer[:]); nil == err || io.ErrUnexpectedEOF == err {
if 0 < n {
var result struct {
Success bool `json:"success"`
ChallengeTS string `json:"challenge_ts"`
Hostname string `json:"hostname"`
Score float32 `json:"score"`
ErrorCodes []string `json:"error-codes"`
}
//
if err := json.Unmarshal(buffer[:n], &result); nil == err {
if result.Success {
if 0.6 <= result.Score {
return true
} else {
logs.Error("result score: %f", result.Score)
}
} else {
logs.Error("result success: false")
}
} else {
logs.Error(err)
}
} else {
logs.Error("read empty")
}
} else {
logs.Error(err)
}
} else {
logs.Error("http error: %d", resp.StatusCode)
}
} else {
logs.Error(err)
}
}
return false
}
return true
}
func (this *HostList) IsAuthLogin(w http.ResponseWriter, r *http.Request, domain string, rule *HTTPSRule) bool {
if nil != w && nil != r && "" != domain && nil != rule {
if "" != rule.AuthBase64 {
for _, item := range rule.AnonymousDir {
if strings.HasPrefix(r.URL.Path, item) {
return true
}
}
if list := r.Cookies(); 0 < len(list) {
for _, item := range list {
if this.mRegexpCookie.MatchString(item.Name) {
if "" != item.Value {
//
hash.SetGobFormat(false)
// 比对结果
if hash.HashToString("sha1", rule.AuthBase64,
item.Name[13:23],
this.mCookieSID) == item.Value {
// 修改有效期
item.Path = "/"
item.MaxAge = this.mCookieValidity
item.HttpOnly = true
// 更新cookie
http.SetCookie(w, item)
//
return true
}
}
// 修改有效期
item.MaxAge = -1
// 废除cookie
http.SetCookie(w, item)
}
}
}
} else {
return true
}
}
return false
}
func (this *HostList) SetSSLAddr(addr net.Addr) {
this.mSSLAddr = addr
}
func (this *HostList) TLSConfig() *tls.Config {
if "" != this.mGlobalCertFilepath && "" != this.mGlobalKeyFilepath {
if f, err := os.Open(this.mGlobalCertFilepath); nil == err {
if path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", f.Fd())); nil == err {
this.mGlobalCertFilepath = path
}
f.Close()
} else {
this.mGlobalCertFilepath = filepath.Join(rootDir, filepath.Base(this.mGlobalCertFilepath))
}
if f, err := os.Open(this.mGlobalKeyFilepath); nil == err {
if path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", f.Fd())); nil == err {
this.mGlobalKeyFilepath = path
}
f.Close()
} else {
this.mGlobalKeyFilepath = filepath.Join(rootDir, filepath.Base(this.mGlobalKeyFilepath))
}
if f, err := os.Open(this.mGlobalCAFilepath); nil == err {
if path, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", f.Fd())); nil == err {
this.mGlobalCAFilepath = path
}
f.Close()
} else {
this.mGlobalCAFilepath = filepath.Join(rootDir, filepath.Base(this.mGlobalCAFilepath))
}
//
logs.Info(this.mGlobalCertFilepath)
logs.Info(this.mGlobalKeyFilepath)
logs.Info(this.mGlobalCAFilepath)
//
if certPem, err := ioutil.ReadFile(this.mGlobalCertFilepath); nil == err {
if keyPem, err := ioutil.ReadFile(this.mGlobalKeyFilepath); nil == err {
if cert, err := tls.X509KeyPair(certPem, keyPem); nil == err {
//
if caPem, err := ioutil.ReadFile(this.mGlobalCAFilepath); nil == err {
//
pool := x509.NewCertPool()
//
pool.AppendCertsFromPEM(caPem)
//
return &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
}
}
//
return &tls.Config{
Certificates: []tls.Certificate{cert},
}
} else {
logs.Error(err)
}
} else {
logs.Error(err)
}
} else {
logs.Error(err)
}
}
if nil == this.mAutoCert {
this.mAutoCert = autocert.NewAutoCertManager()
}
return this.mAutoCert.TLSConfig()
}
func (this *HostList) Accept() (net.Conn, error) {
if conn, ok := <-this.mCC; ok {
return conn, nil
}
return nil, syscall.ENETDOWN
}
func (this *HostList) Addr() net.Addr {
return this.mSSLAddr
}
func (this *HostList) Close() error {
close(this.mCC)
return nil
}
// https2http代理
func (this *HostList) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if nil != r.TLS {
if this.MasterDomain == r.Host {
this.ServeMaster(w, r)
return
} else if rule, _ := this.mListHTTPS[r.Host]; nil != rule {
if nil != rule.PluginHandler {
//
rule.PluginHandler(w, r)
// 退出
return
} else if rule.Redirect {
//
this.HttpRedirect(w, rule.Target)
//
return
} else if rule.AutoCert {
if !this.IsAuthLogin(w, r, r.Host, rule) {
if "GET" == r.Method {
if referer := r.Header.Get("Referer"); "" != referer {
if u, err := url.Parse(referer); nil == err {
if code := u.Query().Get("code"); "" != code {
if this.CheckAuthCodeOK(code) {
//
timeunix := time.Now().Unix()
//
hash.SetGobFormat(false)
//
http.SetCookie(w, &http.Cookie{
Name: fmt.Sprintf("__auth_token_%d__", timeunix),
Value: hash.HashToString("sha1", rule.AuthBase64,
timeunix,
this.mCookieSID),
Path: "/",
MaxAge: this.mCookieValidity,
HttpOnly: true,
})
//
this.HttpRedirect(w, r.URL.RequestURI())
//
return
}
}
}
}
if "" != this.MasterDomain {
//
v := url.Values{}
//
v.Add("redirect", fmt.Sprintf("https://%s%s", r.Host, r.URL.RequestURI()))
//
u := url.URL{
Scheme: "https",
Host: this.MasterDomain,
Path: "/login",
RawQuery: v.Encode(),
}
//
this.HttpRedirect(w, u.String())
//
return
}
}
//
w.WriteHeader(http.StatusUnauthorized)
//
return
}
if hj, ok := w.(http.Hijacker); ok {
// 得到原始连接
if conn_remote, _, err := hj.Hijack(); nil == err {
// 退出时关闭
defer conn_remote.Close()
// 连接目标
if conn_local, err := net.DialTimeout("tcp", rule.Target, 30*time.Second); nil == err {
// 退出时关闭
defer conn_local.Close()
// 修改请求
r.URL.Scheme = "http"
r.TLS = nil
// 写请求
r.Write(conn_local)
//
fast_io.FastCopy(conn_remote, conn_local)
//
return
} else {
// 输出错误
logs.Warn(err)
}
} else {
// 输出错误
logs.Warn(err)
}
} else {
// 输出错误
logs.Warn("unable to hijack connection")
}
}
// HTTP响应,转发请求失败
this.HttpError(w, http.StatusBadGateway)
// 退出
return
}
// HTTP响应,未找到
this.HttpError(w, http.StatusNotFound)
// 退出
return
}
// HTTP响应,内部服务错误
this.HttpError(w, http.StatusInternalServerError)
}
func (this *HostList) ServeMaster(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/":
if this.CheckHTTPAuth(w, r) {
var n int
this.RLock()
n = len(this.mStat)
this.RUnlock()
if 0 < n {
var i int
list := make([]string, 0, n)
fmt.Fprint(w, `<html>`)
fmt.Fprint(w, `<head>`)
fmt.Fprint(w, `<meta charset="UTF-8">`)
fmt.Fprint(w, `<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">`)
fmt.Fprint(w, `<meta http-equiv="Cache-Control" content="no-cache" />`)
fmt.Fprint(w, `<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">`)
fmt.Fprint(w, `<style>`)
fmt.Fprint(w, `td { text-align: center; }`)
fmt.Fprint(w, `.domain { width: 50%; background-color: #F8F8F8; }`)
fmt.Fprint(w, `.red { background-color: #FFB5B5; }`)
fmt.Fprint(w, `.green { background-color: #CEFFCE; }`)
fmt.Fprint(w, `</style>`)
fmt.Fprint(w, `</head>`)
fmt.Fprint(w, `<body>`)
fmt.Fprint(w, `<div>`)