-
Notifications
You must be signed in to change notification settings - Fork 21
/
http_request.go
1749 lines (1534 loc) · 41.5 KB
/
http_request.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 nodes
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
teaconst "github.com/TeaOSLab/EdgeNode/internal/const"
"github.com/TeaOSLab/EdgeNode/internal/iplibrary"
"github.com/TeaOSLab/EdgeNode/internal/metrics"
"github.com/TeaOSLab/EdgeNode/internal/stats"
"github.com/TeaOSLab/EdgeNode/internal/utils"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
// 环境变量
var HOSTNAME, _ = os.Hostname()
// errors
var errWritingToClient = errors.New("writing to client error")
// HTTPRequest HTTP请求
type HTTPRequest struct {
requestId string
// 外部参数
RawReq *http.Request
RawWriter http.ResponseWriter
ReqServer *serverconfigs.ServerConfig
ReqHost string // 请求的Host
ServerName string // 实际匹配到的Host
ServerAddr string // 实际启动的服务器监听地址
IsHTTP bool
IsHTTPS bool
// 共享参数
nodeConfig *nodeconfigs.NodeConfig
// ln request
isLnRequest bool
lnRemoteAddr string
// 内部参数
isSubRequest bool
writer *HTTPWriter
web *serverconfigs.HTTPWebConfig // Web配置,重要提示:由于引用了别的共享的配置,所以操作中只能读取不要修改
reverseProxyRef *serverconfigs.ReverseProxyRef // 反向代理引用
reverseProxy *serverconfigs.ReverseProxyConfig // 反向代理配置,重要提示:由于引用了别的共享的配置,所以操作中只能读取不要修改
rawURI string // 原始的URI
uri string // 经过rewrite等运算之后的URI
varMapping map[string]string // 变量集合
requestFromTime time.Time // 请求开始时间
requestCost float64 // 请求耗时
filePath string // 请求的文件名,仅在读取Root目录下的内容时不为空
origin *serverconfigs.OriginConfig // 源站
originAddr string // 源站实际地址
errors []string // 错误信息
rewriteRule *serverconfigs.HTTPRewriteRule // 匹配到的重写规则
rewriteReplace string // 重写规则的目标
rewriteIsExternalURL bool // 重写目标是否为外部URL
remoteAddr string // 计算后的RemoteAddr
cacheRef *serverconfigs.HTTPCacheRef // 缓存设置
cacheKey string // 缓存使用的Key
isCached bool // 是否已经被缓存
cacheCanTryStale bool // 是否可以尝试使用Stale缓存
isAttack bool // 是否是攻击请求
requestBodyData []byte // 读取的Body内容
// WAF相关
firewallPolicyId int64
firewallRuleGroupId int64
firewallRuleSetId int64
firewallRuleId int64
firewallActions []string
wafHasRequestBody bool
tags []string
logAttrs map[string]string
disableLog bool // 是否在当前请求中关闭Log
forceLog bool // 是否强制记录日志
// script相关操作
isDone bool
}
// 初始化
func (this *HTTPRequest) init() {
this.writer = NewHTTPWriter(this, this.RawWriter)
this.web = &serverconfigs.HTTPWebConfig{
IsOn: true,
}
// this.uri = this.RawReq.URL.RequestURI()
// 之所以不使用RequestURI(),是不想让URL中的Path被Encode
var urlPath = this.RawReq.URL.Path
if this.ReqServer.Web != nil && this.ReqServer.Web.MergeSlashes {
urlPath = utils.CleanPath(urlPath)
this.web.MergeSlashes = true
}
if len(this.RawReq.URL.RawQuery) > 0 {
this.uri = urlPath + "?" + this.RawReq.URL.RawQuery
} else {
this.uri = urlPath
}
this.rawURI = this.uri
this.varMapping = map[string]string{
// 缓存相关初始化
"cache.status": "BYPASS",
"cache.age": "0",
"cache.key": "",
"cache.policy.name": "",
"cache.policy.id": "0",
"cache.policy.type": "",
}
this.logAttrs = map[string]string{}
this.requestFromTime = time.Now()
this.requestId = httpRequestNextId()
}
// Do 执行请求
func (this *HTTPRequest) Do() {
// 初始化
this.init()
// 当前服务的反向代理配置
if this.ReqServer.ReverseProxyRef != nil && this.ReqServer.ReverseProxy != nil {
this.reverseProxyRef = this.ReqServer.ReverseProxyRef
this.reverseProxy = this.ReqServer.ReverseProxy
}
// Web配置
err := this.configureWeb(this.ReqServer.Web, true, 0)
if err != nil {
this.write50x(err, http.StatusInternalServerError, "Failed to configure the server", "配置服务失败", false)
this.doEnd()
return
}
// 是否为低级别节点
this.isLnRequest = this.checkLnRequest()
// 回调事件
this.onInit()
if this.writer.isFinished {
this.doEnd()
return
}
// 处理健康检查
var isHealthCheck = false
var healthCheckKey = this.RawReq.Header.Get(serverconfigs.HealthCheckHeaderName)
if len(healthCheckKey) > 0 {
if this.doHealthCheck(healthCheckKey, &isHealthCheck) {
this.doEnd()
return
}
}
if !this.isLnRequest {
// 特殊URL处理
if len(this.rawURI) > 1 && this.rawURI[1] == '.' {
// ACME
// TODO 需要配置是否启用ACME检测
if strings.HasPrefix(this.rawURI, "/.well-known/acme-challenge/") {
if this.doACME() {
this.doEnd()
return
}
}
}
// 套餐
if this.ReqServer.UserPlan != nil && !this.ReqServer.UserPlan.IsAvailable() {
this.doPlanExpires()
this.doEnd()
return
}
// 流量限制
if this.ReqServer.TrafficLimit != nil && this.ReqServer.TrafficLimit.IsOn && !this.ReqServer.TrafficLimit.IsEmpty() && this.ReqServer.TrafficLimitStatus != nil && this.ReqServer.TrafficLimitStatus.IsValid() {
this.doTrafficLimit()
this.doEnd()
return
}
// UAM
if !isHealthCheck {
if this.web.UAM != nil {
if this.web.UAM.IsOn {
if this.doUAM() {
this.doEnd()
return
}
}
} else if this.ReqServer.UAM != nil && this.ReqServer.UAM.IsOn {
this.web.UAM = this.ReqServer.UAM
if this.doUAM() {
this.doEnd()
return
}
}
}
// WAF
if this.web.FirewallRef != nil && this.web.FirewallRef.IsOn {
if this.doWAFRequest() {
this.doEnd()
return
}
}
// 访问控制
if !this.isSubRequest && this.web.Auth != nil && this.web.Auth.IsOn {
if this.doAuth() {
this.doEnd()
return
}
}
// 自动跳转到HTTPS
if this.IsHTTP && this.web.RedirectToHttps != nil && this.web.RedirectToHttps.IsOn {
if this.doRedirectToHTTPS(this.web.RedirectToHttps) {
this.doEnd()
return
}
}
// Compression
if this.web.Compression != nil && this.web.Compression.IsOn && this.web.Compression.Level > 0 {
this.writer.SetCompression(this.web.Compression)
}
}
// 开始调用
this.doBegin()
// 关闭写入
this.writer.Close()
// 结束调用
this.doEnd()
}
// 开始调用
func (this *HTTPRequest) doBegin() {
// 是否找不到域名匹配
if this.ReqServer.Id == 0 {
this.doMismatch()
return
}
if !this.isLnRequest {
// 处理request limit
if this.web.RequestLimit != nil &&
this.web.RequestLimit.IsOn {
if this.doRequestLimit() {
return
}
}
// 处理requestBody
if this.RawReq.ContentLength > 0 &&
this.web.AccessLogRef != nil &&
this.web.AccessLogRef.IsOn &&
this.web.AccessLogRef.ContainsField(serverconfigs.HTTPAccessLogFieldRequestBody) {
var err error
this.requestBodyData, err = io.ReadAll(io.LimitReader(this.RawReq.Body, AccessLogMaxRequestBodySize))
if err != nil {
this.write50x(err, http.StatusBadGateway, "Failed to read request body for access log", "为访问日志读取请求Body失败", false)
return
}
this.RawReq.Body = io.NopCloser(io.MultiReader(bytes.NewBuffer(this.requestBodyData), this.RawReq.Body))
}
// 跳转
if len(this.web.HostRedirects) > 0 {
if this.doHostRedirect() {
return
}
}
// 临时关闭页面
if this.web.Shutdown != nil && this.web.Shutdown.IsOn {
this.doShutdown()
return
}
}
// 缓存
if this.web.Cache != nil && this.web.Cache.IsOn {
if this.doCacheRead(false) {
return
}
}
if !this.isLnRequest {
// 重写规则
if this.rewriteRule != nil {
if this.doRewrite() {
return
}
}
// Fastcgi
if this.web.FastcgiRef != nil && this.web.FastcgiRef.IsOn && len(this.web.FastcgiList) > 0 {
if this.doFastcgi() {
return
}
}
// root
if this.web.Root != nil && this.web.Root.IsOn {
// 如果处理成功,则终止请求的处理
if this.doRoot() {
return
}
// 如果明确设置了终止,则也会自动终止
if this.web.Root.IsBreak {
return
}
}
}
// Reverse Proxy
if this.reverseProxyRef != nil && this.reverseProxyRef.IsOn && this.reverseProxy != nil && this.reverseProxy.IsOn {
this.doReverseProxy()
return
}
// 返回404页面
this.write404()
}
// 结束调用
func (this *HTTPRequest) doEnd() {
// 记录日志
this.log()
// 流量统计
// TODO 增加是否开启开关
if this.ReqServer != nil && this.ReqServer.Id > 0 {
var countCached int64 = 0
var cachedBytes int64 = 0
var countAttacks int64 = 0
var attackBytes int64 = 0
if this.isCached {
countCached = 1
cachedBytes = this.writer.SentBodyBytes() + this.writer.SentHeaderBytes()
}
if this.isAttack {
countAttacks = 1
attackBytes = this.CalculateSize()
}
stats.SharedTrafficStatManager.Add(this.ReqServer.Id, this.ReqHost, this.writer.SentBodyBytes()+this.writer.SentHeaderBytes(), cachedBytes, 1, countCached, countAttacks, attackBytes, this.ReqServer.ShouldCheckTrafficLimit(), this.ReqServer.PlanId())
// 指标
if metrics.SharedManager.HasHTTPMetrics() {
this.doMetricsResponse()
}
// 统计
if this.web.StatRef != nil && this.web.StatRef.IsOn {
// 放到最后执行
this.doStat()
}
}
}
// RawURI 原始的请求URI
func (this *HTTPRequest) RawURI() string {
return this.rawURI
}
// 配置
func (this *HTTPRequest) configureWeb(web *serverconfigs.HTTPWebConfig, isTop bool, redirects int) error {
if web == nil || !web.IsOn {
return nil
}
// 防止跳转次数过多
if redirects > 8 {
return errors.New("too many redirects")
}
redirects++
// uri
rawPath := ""
rawQuery := ""
qIndex := strings.Index(this.uri, "?") // question mark index
if qIndex > -1 {
rawPath = this.uri[:qIndex]
rawQuery = this.uri[qIndex+1:]
} else {
rawPath = this.uri
}
// redirect
if web.RedirectToHttps != nil && (web.RedirectToHttps.IsPrior || isTop) {
this.web.RedirectToHttps = web.RedirectToHttps
}
// pages
if len(web.Pages) > 0 {
this.web.Pages = web.Pages
}
// shutdown
if web.Shutdown != nil && (web.Shutdown.IsPrior || isTop) {
this.web.Shutdown = web.Shutdown
}
// headers
if web.RequestHeaderPolicyRef != nil && (web.RequestHeaderPolicyRef.IsPrior || isTop) && web.RequestHeaderPolicy != nil {
// TODO 现在是只能选一个有效的设置,未来可以选择是否合并多级别的设置
this.web.RequestHeaderPolicy = web.RequestHeaderPolicy
}
if web.ResponseHeaderPolicyRef != nil && (web.ResponseHeaderPolicyRef.IsPrior || isTop) && web.ResponseHeaderPolicy != nil {
// TODO 现在是只能选一个有效的设置,未来可以选择是否合并多级别的设置
this.web.ResponseHeaderPolicy = web.ResponseHeaderPolicy
}
// root
if web.Root != nil && (web.Root.IsPrior || isTop) {
this.web.Root = web.Root
}
// remote addr
if web.RemoteAddr != nil && (web.RemoteAddr.IsPrior || isTop) && web.RemoteAddr.IsOn {
this.web.RemoteAddr = web.RemoteAddr
}
// charset
if web.Charset != nil && (web.Charset.IsPrior || isTop) {
this.web.Charset = web.Charset
}
// websocket
if web.WebsocketRef != nil && (web.WebsocketRef.IsPrior || isTop) {
this.web.WebsocketRef = web.WebsocketRef
this.web.Websocket = web.Websocket
}
// compression
if web.Compression != nil && (web.Compression.IsPrior || isTop) {
this.web.Compression = web.Compression
}
// webp
if web.WebP != nil && (web.WebP.IsPrior || isTop) {
this.web.WebP = web.WebP
}
// cache
if web.Cache != nil && (web.Cache.IsPrior || isTop) {
this.web.Cache = web.Cache
}
// waf
if web.FirewallRef != nil && (web.FirewallRef.IsPrior || isTop) {
this.web.FirewallRef = web.FirewallRef
if web.FirewallPolicy != nil {
this.web.FirewallPolicy = web.FirewallPolicy
}
}
// access log
if web.AccessLogRef != nil && (web.AccessLogRef.IsPrior || isTop) {
this.web.AccessLogRef = web.AccessLogRef
}
// host redirects
if len(web.HostRedirects) > 0 {
this.web.HostRedirects = web.HostRedirects
}
// stat
if web.StatRef != nil && (web.StatRef.IsPrior || isTop) {
this.web.StatRef = web.StatRef
}
// fastcgi
if web.FastcgiRef != nil && (web.FastcgiRef.IsPrior || isTop) {
this.web.FastcgiRef = web.FastcgiRef
this.web.FastcgiList = web.FastcgiList
}
// auth
if web.Auth != nil && (web.Auth.IsPrior || isTop) {
this.web.Auth = web.Auth
}
// request limit
if web.RequestLimit != nil && (web.RequestLimit.IsPrior || isTop) {
this.web.RequestLimit = web.RequestLimit
}
// request scripts
if web.RequestScripts != nil {
if this.web.RequestScripts == nil {
this.web.RequestScripts = &serverconfigs.HTTPRequestScriptsConfig{
InitGroup: web.RequestScripts.InitGroup,
RequestGroup: web.RequestScripts.RequestGroup,
} // 不要直接赋值,需要复制,防止在运行时被修改
} else {
if web.RequestScripts.InitGroup != nil && (web.RequestScripts.InitGroup.IsPrior || isTop) {
if this.web.RequestScripts == nil {
this.web.RequestScripts = &serverconfigs.HTTPRequestScriptsConfig{}
}
this.web.RequestScripts.InitGroup = web.RequestScripts.InitGroup
}
if web.RequestScripts.RequestGroup != nil && (web.RequestScripts.RequestGroup.IsPrior || isTop) {
if this.web.RequestScripts == nil {
this.web.RequestScripts = &serverconfigs.HTTPRequestScriptsConfig{}
}
this.web.RequestScripts.RequestGroup = web.RequestScripts.RequestGroup
}
}
}
// UAM
if web.UAM != nil && (web.UAM.IsPrior || isTop) {
this.web.UAM = web.UAM
}
// 重写规则
if len(web.RewriteRefs) > 0 {
for index, ref := range web.RewriteRefs {
if !ref.IsOn {
continue
}
rewriteRule := web.RewriteRules[index]
if !rewriteRule.IsOn {
continue
}
if replace, varMapping, isMatched := rewriteRule.MatchRequest(rawPath, this.Format); isMatched {
this.addVarMapping(varMapping)
this.rewriteRule = rewriteRule
if rewriteRule.WithQuery {
queryIndex := strings.Index(replace, "?")
if queryIndex > -1 {
if len(rawQuery) > 0 {
replace = replace[:queryIndex] + "?" + rawQuery + "&" + replace[queryIndex+1:]
}
} else {
if len(rawQuery) > 0 {
replace += "?" + rawQuery
}
}
}
this.rewriteReplace = replace
// 如果是外部URL直接返回
if rewriteRule.IsExternalURL(replace) {
this.rewriteIsExternalURL = true
return nil
}
// 如果是内部URL继续解析
if replace == this.uri {
// URL不变,则停止解析,防止无限循环跳转
return nil
}
this.uri = replace
// 终止解析的几个个条件:
// isBreak = true
// mode = redirect
// replace = external url
// replace = uri
if rewriteRule.IsBreak || rewriteRule.Mode == serverconfigs.HTTPRewriteModeRedirect {
return nil
}
return this.configureWeb(web, isTop, redirects+1)
}
}
}
// locations
if len(web.LocationRefs) > 0 {
var resultLocation *serverconfigs.HTTPLocationConfig
for index, ref := range web.LocationRefs {
if !ref.IsOn {
continue
}
location := web.Locations[index]
if !location.IsOn {
continue
}
if varMapping, isMatched := location.Match(rawPath, this.Format); isMatched {
// 检查专属域名
if len(location.Domains) > 0 && !configutils.MatchDomains(location.Domains, this.ReqHost) {
continue
}
if len(varMapping) > 0 {
this.addVarMapping(varMapping)
}
resultLocation = location
if location.IsBreak {
break
}
}
}
if resultLocation != nil {
// reset rewrite rule
this.rewriteRule = nil
// Reverse Proxy
if resultLocation.ReverseProxyRef != nil && resultLocation.ReverseProxyRef.IsPrior {
this.reverseProxyRef = resultLocation.ReverseProxyRef
this.reverseProxy = resultLocation.ReverseProxy
}
// Web
if resultLocation.Web != nil {
err := this.configureWeb(resultLocation.Web, false, redirects+1)
if err != nil {
return err
}
}
}
}
return nil
}
// Format 利用请求参数格式化字符串
func (this *HTTPRequest) Format(source string) string {
if len(source) == 0 {
return ""
}
var hasVarMapping = len(this.varMapping) > 0
return configutils.ParseVariables(source, func(varName string) string {
// 自定义变量
if hasVarMapping {
value, found := this.varMapping[varName]
if found {
return value
}
}
// 请求变量
switch varName {
case "edgeVersion":
return teaconst.Version
case "remoteAddr":
return this.requestRemoteAddr(true)
case "remoteAddrValue":
return this.requestRemoteAddr(false)
case "rawRemoteAddr":
addr := this.RawReq.RemoteAddr
host, _, err := net.SplitHostPort(addr)
if err == nil {
addr = host
}
return addr
case "remotePort":
return strconv.Itoa(this.requestRemotePort())
case "remoteUser":
return this.requestRemoteUser()
case "requestId":
return this.requestId
case "requestURI", "requestUri":
return this.rawURI
case "requestURL":
var scheme = "http"
if this.IsHTTPS {
scheme = "https"
}
return scheme + "://" + this.ReqHost + this.rawURI
case "requestPath":
return this.Path()
case "requestPathExtension":
return filepath.Ext(this.Path())
case "requestLength":
return strconv.FormatInt(this.requestLength(), 10)
case "requestTime":
return fmt.Sprintf("%.6f", this.requestCost)
case "requestMethod":
return this.RawReq.Method
case "requestFilename":
filename := this.requestFilename()
if len(filename) > 0 {
return filename
}
if this.web.Root != nil && this.web.Root.IsOn {
return filepath.Clean(this.web.Root.Dir + this.Path())
}
return ""
case "scheme":
if this.IsHTTP {
return "http"
} else {
return "https"
}
case "serverProtocol", "proto":
return this.RawReq.Proto
case "bytesSent":
return strconv.FormatInt(this.writer.SentBodyBytes(), 10) // TODO 加上Header长度
case "bodyBytesSent":
return strconv.FormatInt(this.writer.SentBodyBytes(), 10)
case "status":
return strconv.Itoa(this.writer.StatusCode())
case "statusMessage":
return http.StatusText(this.writer.StatusCode())
case "timeISO8601":
return this.requestFromTime.Format("2006-01-02T15:04:05.000Z07:00")
case "timeLocal":
return this.requestFromTime.Format("2/Jan/2006:15:04:05 -0700")
case "msec":
return fmt.Sprintf("%.6f", float64(this.requestFromTime.Unix())+float64(this.requestFromTime.Nanosecond())/1000000000)
case "timestamp":
return strconv.FormatInt(this.requestFromTime.Unix(), 10)
case "host":
return this.ReqHost
case "referer":
return this.RawReq.Referer()
case "referer.host":
u, err := url.Parse(this.RawReq.Referer())
if err == nil {
return u.Host
}
return ""
case "userAgent":
return this.RawReq.UserAgent()
case "contentType":
return this.requestContentType()
case "request":
return this.requestString()
case "cookies":
return this.requestCookiesString()
case "isArgs":
if strings.Contains(this.uri, "?") {
return "?"
}
return ""
case "args", "queryString":
return this.requestQueryString()
case "headers":
return this.requestHeadersString()
case "serverName":
return this.ServerName
case "serverPort":
return strconv.Itoa(this.requestServerPort())
case "hostname":
return HOSTNAME
case "documentRoot":
if this.web.Root != nil {
return this.web.Root.Dir
}
return ""
}
dotIndex := strings.Index(varName, ".")
if dotIndex < 0 {
return "${" + varName + "}"
}
prefix := varName[:dotIndex]
suffix := varName[dotIndex+1:]
// cookie.
if prefix == "cookie" {
return this.requestCookie(suffix)
}
// arg.
if prefix == "arg" {
return this.requestQueryParam(suffix)
}
// header.
if prefix == "header" || prefix == "http" {
return this.requestHeader(suffix)
}
// response.
if prefix == "response" {
switch suffix {
case "contentType":
return this.writer.Header().Get("Content-Type")
}
// response.xxx.xxx
dotIndex := strings.Index(suffix, ".")
if dotIndex < 0 {
return "${" + varName + "}"
}
switch suffix[:dotIndex] {
case "header":
return this.writer.Header().Get(suffix[dotIndex+1:])
}
}
// origin.
if prefix == "origin" {
if this.origin != nil {
switch suffix {
case "address", "addr":
return this.originAddr
case "host":
addr := this.originAddr
index := strings.Index(addr, ":")
if index > -1 {
return addr[:index]
} else {
return ""
}
case "id":
return strconv.FormatInt(this.origin.Id, 10)
case "scheme", "protocol":
return this.origin.Addr.Protocol.String()
case "code":
return this.origin.Code
}
}
return ""
}
// node
if prefix == "node" {
switch suffix {
case "id":
return strconv.FormatInt(this.nodeConfig.Id, 10)
case "name":
return this.nodeConfig.Name
case "role":
return teaconst.Role
}
}
// host
if prefix == "host" {
pieces := strings.Split(this.ReqHost, ".")
switch suffix {
case "first":
if len(pieces) > 0 {
return pieces[0]
}
return ""
case "last":
if len(pieces) > 0 {
return pieces[len(pieces)-1]
}
return ""
case "0":
if len(pieces) > 0 {
return pieces[0]
}
return ""
case "1":
if len(pieces) > 1 {
return pieces[1]
}
return ""
case "2":
if len(pieces) > 2 {
return pieces[2]
}
return ""
case "3":
if len(pieces) > 3 {
return pieces[3]
}
return ""
case "4":
if len(pieces) > 4 {
return pieces[4]
}
return ""
case "-1":
if len(pieces) > 0 {
return pieces[len(pieces)-1]
}
return ""
case "-2":
if len(pieces) > 1 {
return pieces[len(pieces)-2]
}
return ""
case "-3":
if len(pieces) > 2 {
return pieces[len(pieces)-3]
}
return ""
case "-4":
if len(pieces) > 3 {
return pieces[len(pieces)-4]
}
return ""
case "-5":
if len(pieces) > 4 {
return pieces[len(pieces)-5]
}
return ""
}
}
// geo
if prefix == "geo" {
result, _ := iplibrary.SharedLibrary.Lookup(this.requestRemoteAddr(true))
switch suffix {
case "country.name":
if result != nil {
return result.Country
}
return ""
case "country.id":
if result != nil {
return types.String(iplibrary.SharedCountryManager.Lookup(result.Country))
}
return "0"
case "province.name":
if result != nil {
return result.Province
}
return ""
case "province.id":
if result != nil {
return types.String(iplibrary.SharedProvinceManager.Lookup(result.Province))
}
return "0"
case "city.name":
if result != nil {
return result.City
}
return ""
case "city.id":
if result != nil {
var provinceId = iplibrary.SharedProvinceManager.Lookup(result.Province)
if provinceId > 0 {
return types.String(iplibrary.SharedCityManager.Lookup(provinceId, result.City))
} else {
return "0"
}
}
return "0"
}
}
// ips
if prefix == "isp" {
result, _ := iplibrary.SharedLibrary.Lookup(this.requestRemoteAddr(true))
switch suffix {
case "name":
if result != nil {
return result.ISP
}
case "id":
if result != nil {
return types.String(iplibrary.SharedProviderManager.Lookup(result.ISP))
}
return "0"
}
return ""
}
// browser
if prefix == "browser" {
var result = stats.SharedUserAgentParser.Parse(this.RawReq.UserAgent())
switch suffix {
case "os.name":
return result.OS.Name
case "os.version":
return result.OS.Version
case "name":
return result.BrowserName
case "version":